等待线程
[喝小酒的网摘]http://blog.hehehehehe.cn/a/17163.htm
1。使用pthread_cond_wait前要先加锁
2。pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活(pthread_cond_signal发送信号)
3。pthread_cond_wait被激活后会再自动加锁
激活线程:
1。加锁(和等待线程用同一个锁)
2。pthread_cond_signal发送信号
3。解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。
程序示例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int sum;
void* dec(void *argv)
{
pthread_mutex_lock(&lock);
while(sum==0)
{
printf("dec sum=0 ");
pthread_cond_wait(&cond,&lock);
}
sum--;
pthread_mutex_unlock(&lock);
printf("dec sum=%d ",sum);
pthread_exit(NULL);
return 0;
}
void* add(void *argv)
{
pthread_mutex_lock(&lock);
if(sum==0)
{
printf("add sum =0 ");
pthread_cond_signal(&cond);
}
sum++;
pthread_mutex_unlock(&lock);
sleep(1);
sum++;
printf("add sum=%d ",sum);
pthread_exit(NULL);
return 0;
}
int main(int argc,char** argv)
{
pthread_t ptid1,ptid2;
sum = 0;
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&ptid1,NULL,dec,NULL);
pthread_create(&ptid2,NULL,add,NULL);
int counter = 0;
while(counter != 10){
printf("counter: %d ", counter);
sleep(1);
counter++;
}
return 0;
}
运行结果:
dec sum=0
counter: 0
add sum =0
dec sum=0
add sum=1
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9
[喝小酒的网摘]http://blog.hehehehehe.cn/a/17163.htm
1。使用pthread_cond_wait前要先加锁
2。pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活(pthread_cond_signal发送信号)
3。pthread_cond_wait被激活后会再自动加锁
激活线程:
1。加锁(和等待线程用同一个锁)
2。pthread_cond_signal发送信号
3。解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。
程序示例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int sum;
void* dec(void *argv)
{
pthread_mutex_lock(&lock);
while(sum==0)
{
printf("dec sum=0 ");
pthread_cond_wait(&cond,&lock);
}
sum--;
pthread_mutex_unlock(&lock);
printf("dec sum=%d ",sum);
pthread_exit(NULL);
return 0;
}
void* add(void *argv)
{
pthread_mutex_lock(&lock);
if(sum==0)
{
printf("add sum =0 ");
pthread_cond_signal(&cond);
}
sum++;
pthread_mutex_unlock(&lock);
sleep(1);
sum++;
printf("add sum=%d ",sum);
pthread_exit(NULL);
return 0;
}
int main(int argc,char** argv)
{
pthread_t ptid1,ptid2;
sum = 0;
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&ptid1,NULL,dec,NULL);
pthread_create(&ptid2,NULL,add,NULL);
int counter = 0;
while(counter != 10){
printf("counter: %d ", counter);
sleep(1);
counter++;
}
return 0;
}
运行结果:
dec sum=0
counter: 0
add sum =0
dec sum=0
add sum=1
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9
[喝小酒的网摘]http://blog.hehehehehe.cn/a/17163.htm