线程续

pthread_create 创建线程
pthread_self 线程ID
pthread_exit 结束当前的线程。

exit(0) 退出进程。
pthread_join 阻塞等待线程 回收线程资源。

#include 
#include 
#include 
#include 
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;
}
线程同步

定义:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作, 其他线程才能对该内存地址进行操作,而其他线程又处于等待状态。

为了防止数据的混乱,多个控制源去修改一个共享数据的时候。

线程同步:
互斥锁(互斥量)

pthread_mutex_lock 阻塞等待
pthread_mutex_trylock 不阻塞等待

死锁:不是一把锁头。
上图

条件变量

不是一把锁,但是配合互斥锁使用。

int pthread_cond_wait(
pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

1、阻塞等待信号pthread_cond_broadcast()和pthread_cond_signal()
2、互斥锁
1和2绑定一起执行,是个原子操作。
等待完成后释放互斥锁。
重新上锁。

信号量

互斥锁理解为初值为1的锁
初始化N个线程 5
线程1 N-- 4
线程2 N-- 3
线程5 N-- 0
int sem_wait(sem_t *sem);
相当于互斥锁的pthread_mutex_lock
int sem_post(sem_t *sem);
相当于互斥锁的pthread_mutex_unlock

你可能感兴趣的:(线程续)