resource.wait()使线程释放锁并进入wait状态(等待resource.notify() 或 resource.notifyAll(), 不是等待获得resource的锁).
resource.notify()会唤醒一个在resource.wait状态的线程(具体哪个由操作系统调度),使那个线程变为等待resource的锁的状态(即正常的阻塞状态).当调用notify()的线程主动释放掉resource的锁时,被唤醒的线程会去竞争锁.
resource.notifyAll()会唤醒所有在resource.wait状态的线程,使他们进入正常的阻塞状态.
notify与notifyAll的区别在于: 调用notify去唤醒线程,如果之后并没有再调用notify或者notifyAll那么其他再wait状态的线程永远都无法被唤醒.
调用wait,notify,notifyAll之前必须获得resource的锁.
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condition;
int flag;
void* threadNotify(void* v){
sleep(3);
pthread_mutex_lock(&mutex);
for(int i = 0; i < 5; i++){
flag++;
}
if(flag >= 5){
pthread_cond_signal(&condition);
}
for(int i = 0; i < 3; i++){
sleep(1);
printf("threadNotify sleeping %d\n", i);
}
pthread_mutex_unlock(&mutex);
}
void* threadWait(void *v){
pthread_mutex_lock(&mutex);
while(flag < 5){
pthread_cond_wait(&condition, &mutex);
}
printf("this is threadWait\n");
pthread_mutex_unlock(&mutex);
}
int main(){
pthread_cond_init(&condition, NULL);
pthread_mutex_init(&mutex, NULL);
flag = 0;
pthread_t th1, th2;
int ret2 = pthread_create(&th2, NULL, threadWait, NULL);
if(ret2 != 0){
printf("error\n");
}
int ret1 = pthread_create(&th1, NULL, threadNotify, NULL);
if(ret1 != 0){
printf("error\n");
}
pthread_join(th2, NULL);
pthread_join(th1, NULL);
}
结果:
threadNotify sleeping 0
threadNotify sleeping 1
threadNotify sleeping 2
this is threadWait