多线程交替打印

多线程交替打印

#include 
#include 
#include 

#define COUNT 100

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t  cond2 = PTHREAD_COND_INITIALIZER;
static int loop = 1;

void *fun1(void* arg)
{
	while (loop < COUNT) {
		pthread_mutex_lock(&mutex);
		if (loop%2 != 0) {
			printf("1\n");
			loop++;
			pthread_cond_signal(&cond2);
		} else {
			pthread_cond_wait(&cond1, &mutex);
		}
		pthread_mutex_unlock(&mutex);
	}
}

void *fun2(void* arg)
{
	while (loop < COUNT) {
		pthread_mutex_lock(&mutex);
		if (loop % 2 == 0) {
			printf("2\n");
			loop++;
			pthread_cond_signal(&cond1);
		} else {
			pthread_cond_wait(&cond2, &mutex);
		}
		pthread_mutex_unlock(&mutex);
	}
}

int main(void)
{
	pthread_t id1;
	pthread_t id2;
	printf("main thread enter\n");
	
	pthread_create(&id1, NULL, fun1, NULL);
	pthread_create(&id2, NULL, fun2, NULL);
	
	pthread_join(id1, NULL);
	pthread_join(id2, NULL);

	printf("man thread exit\n");
}
  • pthread_cond_wait前要先加锁
  • pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
  • pthread_cond_wait被激活后会再自动加锁

你可能感兴趣的:(Linux)