两个线程交替打印奇偶数

在这里插入代码片
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct
{
	int thread_num;
}My_Arr; 		

int arr[5000];
int flag = 0;
pthread_mutex_t lock; //创建线程锁
int s = 0;
//int s1 = 0;
//int s2 = 0;
void * myfunc1(void * args)
{
	My_Arr * my_arr = (My_Arr*) args;	//加锁,解锁可以放到循环体的外部,可以节省时间
	pthread_mutex_lock(&lock);	//锁住
	printf("This is f_lag is %d\n", flag);
	while(s < 100000000)
	{		
		if(flag == 0)
		{
			printf("This is th1's Display : s = %d\n",s);
		}
		if(flag == 1)
		{
			printf("This is th2's Display : s = %d\n",s);
		}
		s = s + 1;
		
		flag = !flag;
		
	}
	pthread_mutex_unlock(&lock);	//解锁
	return NULL;
}


int main()
{
	int i = 100;
	pthread_mutex_init(&lock, NULL);	//把线程锁初始化
	My_Arr Arr1 = {0};
	My_Arr Arr2 = {1};
	pthread_t th1, th2;
	pthread_create(&th1, NULL, myfunc1, &Arr1);
	pthread_create(&th2, NULL, myfunc1, &Arr2);
	pthread_join(th1,NULL);
	pthread_join(th2,NULL);
	//pthread_join等待该线程结束
	printf("s = %d\n",s);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值