两个线程轮流对一个全局变量执行加1操作并且打印
最近在看多线程编程,想起以前有个电话面试出的题目,今天就写了下,主要是利用互斥变量和条件变量,主线程先执行,然后通知子线程执行,轮流执行++操作,并且打印,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
int num = 0;
pthread_mutex_t mtx;
pthread_cond_t cond;
unsigned char flag = 3; //00000011
static void* threadFunc(void *arg)
{
int loop = *(int*)arg;
while(num < loop)
{
pthread_mutex_lock(&mtx);
while((flag >> 1) & 0x1)
pthread_cond_wait(&cond, &mtx);
++num;
flag &= 0x0;
flag |= 0x2;
printf("subthread:%u ,num=%d\n",pthread_self(),num);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
pthread_mutex_init(&mtx, NULL);
pthread_cond_init(&cond, NULL);
int loop = 200;
pthread_t t;
pthread_create(&t, NULL, threadFunc, &loop);
flag &= 0xfe;
while(num < loop)
{
pthread_mutex_lock(&mtx);
while(flag & 0x1)
{
pthread_cond_wait(&cond, &mtx);
}
++num;
flag &= 0x0;
flag |= 0x1;
printf("main:%u ,i=%d\n",pthread_self(),num);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
}
pthread_join(t, NULL);
pthread_mutex_destroy(&mtx);
pthread_cond_destroy(&cond);
return 0;
}
其实也可以不用条件变量,利用那个标志也能达到同样的效果