http://blog.youkuaiyun.com/Frozen_fish/archive/2007/07/11/1685141.aspx
本文可任意转载,但必须注明作者和出处。
--Linux下多线程编程详解
int pthread_cond_init(pthread_cond_t *
restrict cond,
const pthread_condattr_t *restrict attr);
函数说明:
按attr指定的属性初始化cond条件变量。如果attr为NULL,效果等同于pthread_cond_t cond = PTHREAD_COND_INITIALIZER
函数原型:
int pthread_cond_broadcast(pthread_cond_t *cond);
函数说明:
对所有等待cond这个条件变量的线程解除阻塞。
函数原型:
int pthread_cond_signal(pthread_cond_t *cond);
函数说明:
仅仅解除等待cond这个条件变量的某一个线程的阻塞状态。如果有若干线程挂起等待该条件变量,该调用只唤起一个线程,被唤起的线程是哪一个是不确定的。
函数原型:
int pthread_cond_wait(pthread_cond_t *
restrict cond,
pthread_mutex_t *restrict mutex);
函数说明:
该调用自动阻塞发出调用的当前线程,并等待由参数cond指 定的条件变量,而且为参数mutex指定的互斥体解锁。被阻塞线程直到有其他线程调用pthread_cond_signal或 pthread_cond_broadcast函数置相应的条件变量时,而且获得mutex互斥体才解除阻塞。等待状态下的线程不占用CPU时间。
函数原型:
int pthread_cond_timedwait(pthread_cond_t *
restrict cond,
pthread_mutex_t *
restrict mutex,
const struct timespec *restrict abstime);
函数说明:
该函数自动阻塞当前线程等待参数cond指定的条件变量,并 为参数mutex指定的互斥体解锁。被阻塞的线程被唤起继续执行的条件是:有其他线程对条件变量cond调用pthread_cond_signal函 数;或有其他线程对条件变量cond调用pthread_cond_broadcast;或系统时间到达abstime参数指定的时间;除了前面三个条件 中要有一个被满足外,还要求该线程获得参数mutex指定的互斥体。
函数原型:
int pthread_cond_destroy(pthread_cond_t *cond);
函数说明:
释放cond条件变量占用的资源。
看下面的示例:
//example_5.c
#include <stdio.h>
#include
<pthread.h>

pthread_t pt1,pt2;
pthread_mutex_t mu;
pthread_cond_t cond;
int i = 1
;
void * decrease(void *
arg)
{
while(1)
{
pthread_mutex_lock(&mu);
if(++i)
{
printf("%d ",i);
if(i != 1) printf("Error ");
pthread_cond_broadcast(&cond);
pthread_cond_wait(&cond,&mu);
}
sleep(1);
pthread_mutex_unlock(&mu);
}
}

void * increase(void *
arg)
{
while(1)
{
pthread_mutex_lock(&mu);
if(i--)
{
printf("%d ",i);
if(i != 0) printf("Error ");
pthread_cond_broadcast(&cond);
pthread_cond_wait(&cond,&mu);
}
sleep(1);
pthread_mutex_unlock(&mu);
}
}


int
main()
{
pthread_create(&pt2,NULL,increase,NULL);
pthread_create(&pt1,NULL,decrease,NULL);
pthread_join(pt1,NULL);
pthread_join(pt2,NULL);
}
以上我们讲解过了Linux下利用pthread.h头文件的多线程编程知识,下一章中,我们继续讲解关于多线程的深入编程知识,敬请期待。

741

被折叠的 条评论
为什么被折叠?



