#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int i = 1;
int main(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a, NULL, thread1, (void *)NULL);
pthread_create(&t_b, NULL, thread2, (void *)NULL);
pthread_join(t_b, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *junk)
{
for(i = 1; i <= 9; i++)
{
pthread_mutex_lock(&mutex);
if(i % 3 == 0)
pthread_cond_signal(&cond);//条件改变,发送信号通知t_b进程
else
printf("thread1:%d\n", i);
pthread_mutex_unlock(&mutex);
printf("up unlock mutex\n");
sleep(1);
}
}
void *thread2(void *junk)
{
while(i < 9)
{
pthread_mutex_lock(&mutex);
if(i % 3 != 0)
pthread_cond_wait(&cond, &mutex);//等待
printf("thread2:%d\n", i);
pthread_mutex_unlock(&mutex);
printf("down ulock mutex\n");
sleep(1);
}
}
运行结果:
[firephoenix@~]$ ./pthreadcond
thread1:1
up unlock mutex
thread1:2
up unlock mutex
up unlock mutex
thread2:3
down ulock mutex
thread1:4
up unlock mutex
thread1:5
up unlock mutex
up unlock mutex
thread2:6
down ulock mutex
thread1:7
up unlock mutex
thread1:8
up unlock mutex
up unlock mutex
thread2:9
down ulock mutex
分析:
i不是三的倍数的时候.
thread2条件变量阻塞,释放Mutex
thread1加锁,打印thread1:i,释放锁,打印"Up Unlock Mutex"
i为3的倍数的时候,
thread1,加锁,条件变量通知,唤醒条件变量阻塞线程,打印"Up Unlock Mutex"
thread2,被唤醒,加锁,打印"thread2:i",释放锁,打印"Down Ulock Mutex"
所以说函数pthread_cond_wait()调用时,不仅对条件变量起作用,还对互斥锁有作用!