首页 > 系统 > Linux > 正文

linux ptheard 生产者消费者

2024-06-28 13:21:07
字体:
来源:转载
供稿:网友
linux ptheard 生产者消费者1#include<stdio.h>2#include<stdlib.h>3#include<pthread.h>45pthread_mutex_tmutex;6pthread_cond_tcond_full;7pthread_cond_tcond_empty;89intg_iBufSize=0;1011void*thread_PRoducer(void*arg)12{13while(true)14{15printf("thread_producer:pthread_mutex_lock/n");16pthread_mutex_lock(&mutex);17//拿到lock就可以访问,不会冲突,但是不一定满足条件,cond是为了在满足条件的时候通知另一个进程18if(0!=g_iBufSize)//如果条件不满足就调用wait函数等待条件满足19{20printf("thread_producer:pthread_cond_waitcond_empty/n");21pthread_cond_wait(&cond_empty,&mutex);//这句话的前提是先有锁,这时候会自动先解锁,等到时机来临在加锁22}2324//前面的wait操作已经包含了枷锁,这里直接访问25printf("thread_producer>>>>>/n");26g_iBufSize=1;2728printf("thread_producer:pthread_cond_signal/n");29pthread_cond_signal(&cond_full);3031pthread_mutex_unlock(&mutex);32}33returnNULL;34}3536void*thread_consumer(void*arg)37{38while(true)39{40printf("thread_consumer:pthread_mutex_lock/n");41pthread_mutex_lock(&mutex);42if(0==g_iBufSize)43{44printf("thread_consumer:pthread_cond_wait/n");45pthread_cond_wait(&cond_full,&mutex);46}4748printf("thread_consumer>>>/n");49g_iBufSize=0;5051printf("thread_consumer:pthread_cond_signal/n");52pthread_cond_signal(&cond_empty);5354pthread_mutex_unlock(&mutex);5556}57returnNULL;58}5960//g++-obin1-lpthreadmutithread.cpp6162intmain()63{64void*retval1,*retval2;65pthread_tthread_id_1,thread_id_2;6667pthread_mutex_init(&mutex,NULL);68pthread_cond_init(&cond_full,NULL);69pthread_cond_init(&cond_empty,NULL);7071pthread_cond_signal(&cond_empty);72pthread_create(&thread_id_1,NULL,thread_producer,NULL);//intpthread_create(pthread_t*tidp,constpthread_attr_t*attr,(void*)(*start_rtn)(void*),void*arg);73pthread_create(&thread_id_2,NULL,thread_consumer,NULL);7475pthread_join(thread_id_1,&retval1);//阻塞等线程执行完76pthread_join(thread_id_2,&retval2);7778pthread_cond_destroy(&cond_full);79pthread_cond_destroy(&cond_empty);80pthread_mutex_destroy(&mutex);8182return0;83}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表