Linux编程-多线程、同步和互斥(转载)
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; }
相关推荐
farwang 2020-11-25
星愿心愿 2020-11-24
tianhuak 2020-11-24
zhjn0 2020-11-24
昭君出塞 2020-11-23
bluecarrot 2020-11-23
linuxwcj 2020-10-21
以梦为马不负韶华 2020-10-20
彼岸随笔 2020-10-20
yutou0 2020-10-17
applecarelte 2020-10-16
ourtimes 2020-10-16
waterhorse 2020-09-19
MRFENGG 2020-11-11
rainandtear 2020-10-30
kyssfanhui 2020-10-20
liuhangtiant 2020-10-20