pthread_create 創(chuàng)建線程
pthread_self 線程ID
pthread_exit 結(jié)束當(dāng)前的線程萌腿。
exit(0) 退出進(jìn)程。
pthread_join 阻塞等待線程 回收線程資源棠赛。
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
void exit(int);
void sys_err(const char *str){
perror(str);
exit(1);
}
int globl_a = 100;
typedef struct stu
{
int sco;
char name[10];
}mystu;
void* func(void *a){
mystu *pstu = (mystu*)malloc(sizeof(mystu));
pstu->sco = 10;
strcpy(pstu->name,"zhangsan");
return (void*)pstu;
}
int main(){
pthread_t pid_ret;
int ret = pthread_create(&pid_ret, NULL,func, NULL);
if(-1 == ret){
sys_err("pthread_create err");
}
mystu *pstu=NULL;
int retvalue = pthread_join(pid_ret,(void **)&pstu);
if(retvalue == -1){sys_err("pthread_join err\n");}
printf("stu->sco=%d,stu->name=%s\n",pstu->sco,pstu->name);
free(pstu);
pstu=NULL;
printf("*******mainthread********\n");
pthread_exit(NULL);
return 0;
}
線程同步
定義:即當(dāng)有一個(gè)線程在對(duì)內(nèi)存進(jìn)行操作時(shí)哮奇,其他線程都不可以對(duì)這個(gè)內(nèi)存地址進(jìn)行操作膛腐,直到該線程完成操作, 其他線程才能對(duì)該內(nèi)存地址進(jìn)行操作鼎俘,而其他線程又處于等待狀態(tài)哲身。
為了防止數(shù)據(jù)的混亂,多個(gè)控制源去修改一個(gè)共享數(shù)據(jù)的時(shí)候贸伐。
線程同步:
互斥鎖(互斥量)
pthread_mutex_lock 阻塞等待
pthread_mutex_trylock 不阻塞等待
死鎖:不是一把鎖頭勘天。
上圖
條件變量
不是一把鎖,但是配合互斥鎖使用捉邢。
int pthread_cond_wait(
pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
1脯丝、阻塞等待信號(hào)pthread_cond_broadcast()和pthread_cond_signal()
2、互斥鎖
1和2綁定一起執(zhí)行伏伐,是個(gè)原子操作宠进。
等待完成后釋放互斥鎖。
重新上鎖藐翎。
信號(hào)量
互斥鎖理解為初值為1的鎖
初始化N個(gè)線程 5
線程1 N-- 4
線程2 N-- 3
線程5 N-- 0
int sem_wait(sem_t *sem);
相當(dāng)于互斥鎖的pthread_mutex_lock
int sem_post(sem_t *sem);
相當(dāng)于互斥鎖的pthread_mutex_unlock