Linux编程-多线程、同步和互斥(转载)

kuailexiaochuan 2011-11-14

http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html

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

int g_Flag=0;

static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;


void * thread1(void *arg)
{
	printf("%s\n","this is thread1");
	pthread_mutex_lock(&mutex);
	if(g_Flag==2)
		pthread_cond_signal(&cond);
	g_Flag=1;
	pthread_mutex_unlock(&mutex);
	pthread_join(*(pthread_t*)arg,NULL);
	printf("%s\n","exit thread1");
	pthread_exit(0);
}
void *thread2(void *arg)
{
	printf("%s\n","this is thread2");
	pthread_mutex_lock(&mutex);
	if(g_Flag==1)
		pthread_cond_signal(&cond);
	g_Flag=2;
	pthread_mutex_unlock(&mutex);
	printf("%s\n","exit thread2");
	pthread_exit(0);
}
int main()
{
	pthread_t tid1, tid2;
	int rc1=0,rc2=0;
	rc2=pthread_create(&tid2,NULL,thread2,NULL);
	if(rc2!=0)
		printf("thread2 error.\n");
	rc1=pthread_create(&tid1,NULL,thread1,&tid2);
	if(rc1!=0)
		printf("thread1 error.\n");
	pthread_cond_wait(&cond, &mutex);
	return 0;
}
 

相关推荐