子线程循环 3 次,接着主线程循环 6 次,接着又回到子线程循环 3 次,接着再回到主线程又循环6 次,如此循环50次。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

int main_flog = 0;
int sub_flog = 0;

int main_count = 0;
int sub_count = 0;

void *sub_thread_func(void *argv);
void main_thread_func();

int main()
{
	pthread_t tid;
	int ret;
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&cond,NULL);

	ret = pthread_create(&tid,NULL,sub_thread_func,NULL);
	if(ret == -1)
	{
		perror("pthread_create errpr!\n");
		exit(-1);
	}

	main_thread_func();
	ret = pthread_join(tid,NULL);
	if(ret == -1)
	{
		printf("pthread_join error!\n");
		exit(-1);
	}
	return 0;
}
void *sub_thread_func(void *argv)
{
	int i;

	while(1)
	{
		sub_count++;
		for(i = 1; i <= 3; i++)
		{
			printf("sub pthread%d:%d\n",sub_count,i);
		}
		while(1)
		{
			pthread_mutex_lock(&mutex);
			if(main_flog == 1)
			{
	 			pthread_cond_signal(&cond);
				pthread_mutex_unlock(&mutex);
				break;
			}
			pthread_mutex_unlock(&mutex);
		}
		pthread_mutex_lock(&mutex);
		sub_flog = 1;
		pthread_cond_wait(&cond,&mutex);
		sub_flog = 0;
		pthread_mutex_unlock(&mutex);

		//sub_count++;
		if(sub_count >= 50)
		{
			printf("sub_pthread loop 50 times!\n");
			break;
		}
	}
	return (void *)0;
}
void main_thread_func(void)
{
	int i;

	while(1)
	{
		main_count++;
		pthread_mutex_lock(&mutex);
		main_flog = 1;
		pthread_cond_wait(&cond,&mutex);
		main_flog = 0;
		pthread_mutex_unlock(&mutex);

		for(i = 1; i <= 6; i++)
		{
			printf("main	phread%d:%d\n",main_count,i);
		}
		while(1)
		{
			pthread_mutex_lock(&mutex);
			if(sub_flog == 1)
			{
	   			pthread_cond_signal(&cond);
				pthread_mutex_unlock(&mutex);
				break;
			}
			pthread_mutex_unlock(&mutex);
		}
		//main_count++;
		if(main_count >= 50)
		{
			printf("main_phread loop 50 times!\n");
			break;
		}
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值