还是上一道题,这次用条件变量来解
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<signal.h>
#include<stdlib.h>
pthread_t tid[5];
static pthread_mutex_t mt=PTHREAD_MUTEX_INITIALIZER;//初始化锁
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//初始化条件变量
static int num=0;
int cal(int a)
{
if(a>4) return 0;
return a;
}
void *say(void *i)
{
int k=(int)i;
pthread_mutex_lock(&mt);
while(num!=i)
pthread_cond_wait(&cond,&mt);/*pthread_cond_wait(&cond,&mt)函数
每次会先解锁mt, 然后等待COND广播,如果得到COND广播则抢锁mt,进一步判断NUM是否等于I如果等于则该这个线程打印结果了
*/
fprintf(stdout,"[%d]hello!\n",k);
num=cal(i+1);
pthread_cond_broadcast(&cond);//打印完 修改完NUM值 则广播COND 让其他线程判断下当前的NUM值是不是自己的I值
pthread_mutex_unlock(&mt);
pthread_mutex_lock(&mt);
while(num!=i)
pthread_cond_wait(&cond,&mt);
fprintf(stdout,"[%d]bye!\n",k);
num=cal(i+1);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mt);
}
int main()
{
for(int i=0;i<5;i++)
{
int err=pthread_create(tid+i,NULL,say,(void*)i);
if(err<0){fprintf(stderr,"creat err:%s",strerror(err));exit(1);}
}
for(int i=0;i<5;i++)
{
pthread_join(tid[i],NULL);
pthread_mutex_destroy(&mt);
pthread_cond_destroy(&cond);
exit(0);
}
本文展示了一个使用条件变量和互斥锁实现线程间同步的C语言程序实例。通过条件变量,线程能够等待特定条件满足后再继续执行,确保了线程间的正确顺序和资源的正确使用。

被折叠的 条评论
为什么被折叠?



