任务详情
编写多线程程序,主线程中开启两个线程,一个线程打印十个偶数随机数,一个线程打印十个奇数随机数.
代码
点击查看代码
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
int g_num;
int num1=0;
int num2=0;
pthread_mutex_t mutex;
pthread_cond_t cond1,cond2,cond3;
void* Func_p1(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond1,&mutex);
printf("---thread id: %lu , p1 num: %d \n",pthread_self(),g_num);
pthread_mutex_unlock(&mutex);
num1++;
sleep(1);
if(num1>9)break;
}
return NULL;
}
void* Func_p2(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond2,&mutex);
printf("---thread id: %lu , p2 num: %d \n",pthread_self(),g_num);
pthread_mutex_unlock(&mutex);
num2++;
sleep(1);
if(num2>9)break;
}
return NULL;
}
void* Func_p4(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
g_num=rand();
pthread_mutex_unlock(&mutex);
if((g_num % 2) == 0)
pthread_cond_signal(&cond2);
else pthread_cond_signal(&cond1);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t p1,p2,p4;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond1,NULL);
pthread_cond_init(&cond2,NULL);
pthread_create(&p1,NULL,Func_p1,NULL);
pthread_create(&p2,NULL,Func_p2,NULL);
pthread_create(&p4,NULL,Func_p4,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
pthread_join(p4,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
return 0;
}
结果
![](https://img2022.cnblogs.com/blog/2166409/202211/2166409-20221110091708449-42961703.png)