多线程测试

任务详情

编写多线程程序,主线程中开启两个线程,一个线程打印十个偶数随机数,一个线程打印十个奇数随机数.

代码

点击查看代码
#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;
}

结果

posted @ 2022-11-10 09:20  20201221曾思源  阅读(22)  评论(0编辑  收藏  举报