
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
int g_num = 1;
pthread_mutex_t mutex;
pthread_cond_t cond1,cond2;
void* thread1(void* arg)
{
int flag1=0;
while(1)
{
flag1++;
pthread_mutex_lock(&mutex);
srand((unsigned int)time(NULL));
if((g_num=rand()*2+1)>0)
{
printf("%d奇数随机数为:%d\n",flag1,g_num);
}
else{
printf("%d奇数随机数为:%d\n",flag1,-g_num);
}
pthread_cond_signal(&cond2);
pthread_cond_wait(&cond1,&mutex);
pthread_mutex_unlock(&mutex);
sleep(1);
if (flag1==10)
{
break;
}
}
return NULL;
}
void* thread2(void* arg)
{
int flag2=0;
while(1)
{
flag2++;
sleep(1);
srand((unsigned int)time(NULL));
if((g_num=rand()*2)>0)
{
printf("%d偶数随机数为:%d\n", flag2,g_num);
}
else{
printf("%d偶数随机数为:%d\n",flag2,-g_num);
}
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond1);
pthread_cond_wait(&cond2,&mutex);
pthread_mutex_unlock(&mutex);
if (flag2==10)
{
break;
}
}
return NULL;
}
int main()
{
pthread_t p1,p2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond1,NULL);
pthread_cond_init(&cond2,NULL);
pthread_create(&p1,NULL,thread1,NULL);
pthread_create(&p2,NULL,thread2,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~