在这里插入代码片
#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;
}
两个线程交替打印奇偶数
最新推荐文章于 2021-05-06 19:33:14 发布