Linux多线程编程之线程结合互斥锁实现同步

来源:互联网 发布:mac删除酷我音乐 编辑:程序博客网 时间:2024/06/05 00:54
#include <stdio.h>#include <pthread.h>#include <semaphore.h>#include <stdlib.h>//Linux多线程编程之线程结合互斥锁实现同步/*pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //条件变量Int pthread_cond_init(pthread_cond_t   *cond,   pthread_condattr_t       *cond_attr);参数1:条件变量参数2:条件变量属性 NULL//发送一个条件“信号”int pthread_cond_signal(pthread_cond_t *cond);//广播发送条件“信号” int pthread_cond_broadcast(pthread_cond_t *cond);//阻塞等待条件变量“信号”int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);函数内部实现步骤:1.解开前面代码加的互斥锁2.检查是否有条件变量接收,如果有条件变量执行步骤3,继续向下执行,没有条件变量则睡眠(阻塞等待)3.加互斥锁*/static  int val =100;//快速互斥锁:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//读线程执行函数void *pthread_read(void *arg){    while(1){        //加锁        pthread_mutex_lock(&mutex);        printf("thread read run....\n",val);        //等待条件变量        pthread_cond_wait(&cond,&mutex);                printf("pthread read recv cond\n");         //解锁        pthread_mutex_unlock(&mutex);        sleep(1);    }    pthread_exit(NULL);    return NULL;}//写线程执行函数void  *pthread_write(void *arg){    while(1){        //加锁        pthread_mutex_lock(&mutex);        printf("pthread write run..\n");        //等待条件变量        pthread_cond_wait(&cond,&mutex);                printf("phtread wrtite recv cond\n");        //解锁        pthread_mutex_unlock(&mutex);        sleep(2);    }    pthread_exit(NULL);    return NULL;}int main(void){    printf("main thread tid = 0x%x\n",pthread_self());    //初始化互斥锁和条件变量    pthread_mutex_init(&mutex,NULL);    pthread_cond_init(&cond,NULL);    //创建写线程    pthread_t tid2;    pthread_create(&tid2,NULL,pthread_write,NULL);    pthread_detach(tid2);    //创建读线程      pthread_t tid1;    pthread_create(&tid1,NULL,pthread_read,NULL);    pthread_detach(tid1);    sleep(2);  //子线程先运行    //发送条件变量“信号”    //pthread_cond_signal(&cond);    pthread_cond_broadcast(&cond);//  sleep(8);    printf("main pthread exit\n");    pthread_exit(NULL);  //结束主线程        return 0;}/*$ ./a.outmain thread tid = 0xb75de6c0pthread write run..thread read run....main pthread exitphtread wrtite recv condpthread read recv condthread read run....pthread write run..*/
原创粉丝点击