线程同步 实现线程交叉打印
#include <stdio.h>
#include <unistd.h>
#include
<pthread.h>
pthread_cond_t cond =
PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex =
PTHREAD_MUTEX_INITIALIZER;
int gCount = 0;
int gNumber =
0;
void *thread1(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
while(gCount == 1) {
pthread_cond_wait(&cond, &mutex);
}
gCount +=
1;
printf("thread1
gCount:[%d] gNumber:[%d]\r\n", gCount, gNumber++);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void
*thread2(void *arg)
{
while(1) {
pthread_mutex_lock(&mutex);
while(gCount == 0) {
pthread_cond_wait(&cond,
&mutex);
}
gCount -= 1;
printf("thread2 gCount:[%d] gNumber:[%d]\r\n", gCount,
gNumber++);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
/*
*线程条件实现线程同步
*
*/
int
main(void)
{
pthread_t thdId1;
pthread_t thdId2;
pthread_create(&thdId1, NULL, thread1, NULL);
pthread_create(&thdId2, NULL, thread2,
NULL);
pthread_join(thdId1,
NULL);
pthread_join(thdId2, NULL);
return 0;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。