线程同步 实现线程交叉打印
#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;
}
浙公网安备 33010602011771号