wait notify notifyall

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值