posix thread条件变量
概述
- 等待条件变量总是返回锁住的互斥量。
- 条件变量的作用是发送信号,而不是互斥。
- 与条件变量相关的共享数据是“谓词”,如队列满或队列空条件。
- 一个条件变量应该与一个谓词相关。如果一个条件变量与多个谓词相关,或者多个条件变量与一个谓词相关,有可能死锁。
主线程(Main Thread)
|
|
Thread A
|
Thread B
|
创建和销毁条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *condattr);
int pthread_cond_destroy(pthread_cond_t *cond);
- 永远不要copy一个条件变量,因为使用条件变量的备份是不可知的。不过,可以传递条件变量的指针以使不同函数和线程可以使用它来同步。
- 为了获得最好的结果,应该将条件变量与相关的谓词“链接”在一起。
#include<pthread.h>
#include "errors.h" typedef struct my_struct_tag {
pthread_mutex_t mutex;
pthread_cond_t cond;
int value;
} my_struct_t; my_struct_t data = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_COND_INITIALIZER, }; int main(int argc, char* argv[])
{
return ;
}
cond_static.c
#include<pthread.h>
#include "errors.h" typedef struct my_struct_tag {
pthread_mutex_t mutex;
pthread_cond_t cond;
int value;
} my_struct_t; int main(int argc, char* argv[])
{
my_struct_t *data;
int status; data = malloc(sizeof(my_struct_t));
if ( data ==NULL ) {
errno_abort("malloc");
} /*
* init
*/
status = pthread_mutex_init(&data->mutex, NULL);
if ( status != ) {
err_abort(status, "mutex init");
}
status = pthread_cond_init(&data->cond);
if ( status != ) {
err_abort(status, "cond init");
} /*
* destroy
*/
status = pthread_cond_destroy(&data->mutex);
if ( status != ) {
err_abort(status, "destroy cond");
} status = pthread_mutex_destroy(&data->mutex);
if ( status != ) {
err_abort(status, "destroy mutex");
}
free(data);
return status;
}
cond_dynamic.c
等待条件变量
- 在阻塞线程之前,条件变量等待操作将解锁互斥量;而在重新返回线程之前,将再次锁住互斥量。
- 所有并发等待同一个条件变量的线程必须指定同一个相关互斥量。
- 任何条件变量在特定时刻只能与一个互斥量相关联,而互斥量则可以同时与多个条件变量关联。
- 在锁住相关的互斥量之后和在等待条件变量之前,测试谓词是很重要的。
int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex);
int pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, struct timespec* expiration)
#include<time.h>
#include<pthread.h>
#include "errors.h" typedef struct my_struct_tag {
pthread_cond_t cond;
pthread_mutex_t mutex;
int value;
} my_struct_t; my_struct_t data = {
PTHREAD_COND_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, }; int hibernation = ; void* wait_thread(void* arg)
{
int status;
sleep(hibernation);
status = pthread_mutex_lock(&data.mutex);
if (status != )
err_abort(status, "Lock mutex");
data.value = ;
status = pthread_cond_signal(&data.cond);
if (status != )
err_abort(status, "Signal condition");
status = pthread_mutex_unlock(&data.mutex);;
if (status != )
err_abort(status, "Unlock mutex");
return NULL;
} int main(int argc, char* argv[])
{
int status;
pthread_t wait_thread_id;
struct timespec timeout; if (argc > )
hibernation = atoi(argv[]); status = pthread_create(&wait_thread_id, NULL, wait_thread, NULL);
if (status != )
err_abort(status, "Create wait thread"); timeout.tv_sec = time(NULL) + ;
timeout.tv_nsec = ; status = pthread_mutex_lock(&data.mutex);
if (status != )
err_abort(status, "Lock mutex"); while(data.value == ) {
status = pthread_cond_timedwait(&data.cond, &data.mutex, &timeout);
if (status == ETIMEDOUT) {
printf("Condition wait timed out.\n");
break;
}
else if (status != )
err_abort(status, "wait on condition");
}
if (data.value != )
printf("Condition was signaled.\n");
status = pthread_mutex_unlock(&data.mutex);
if (status != )
err_abort(status, "Unlock mutex");
return ;
}
cond.c
唤醒条件变量等待线程
int pthread_cond_signal(pthread_cond_t* cond);
int pthread_cond_broadcast(pthread_cond_t* cond);
- pthread_cond_wait()阻塞调用线程直到指定的条件受信(signaled)。该函数应该在互斥量锁定时调用,当在等待时会自动解锁互斥量。在信号被发送,线程被激活后,互斥量会自动被锁定,当线程结束时,由程序员负责解锁互斥量。
- pthread_cond_signal()函数用于向其他等待在条件变量上的线程发送信号(激活其它线程)。应该在互斥量被锁定后调用。
- 若不止一个线程阻塞在条件变量上,则应用pthread_cond_broadcast()向其它所以线程发生信号。
- 在调用pthread_cond_wait()前调用pthread_cond_signal()会发生逻辑错误。
- 使用这些函数时适当的锁定和解锁相关的互斥量是非常重要的。如:
- 调用pthread_cond_wait()前锁定互斥量失败可能导致线程不会阻塞。
- 调用pthread_cond_signal()后解锁互斥量失败可能会不允许相应的pthread_cond_wait()函数结束(保存阻塞)。
Alarm最终版本
#include<pthread.h>
#include<time.h>
#include"errors.h" typedef struct alarm_tag {
struct alarm_tag *link;
int seconds;
time_t time;
char message[];
} alarm_t; pthread_mutex_t alarm_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t alarm_cond = PTHREAD_COND_INITIALIZER;
alarm_t* alarm_list = NULL;
time_t current_alarm = ; /*
* insert alarm entry on list, in order.
*/
void alarm_insert(alarm_t* alarm)
{
int status;
alarm_t **last, *next; /*
* this routine requires that the caller have locker the alarm_mutex.
*/
last = &alarm_list;
next = *last;
next = *last;
while (next != NULL) {
if (next->time >= alarm->time) {
alarm->link = next;
*last = alarm;
break;
}
last = &next->link;
next = next->link;
}
if (next == NULL) {
*last = alarm;
alarm->link = NULL;
}
#ifdef DEBUG
printf("[list: ");
for (next = alarm_list; next != NULL; next = next->link)
printf("%d(%d)[\"%s\"]", next->time, next->time - time(NULL), next->message);
printf("]\n");
#endif
/*
* wake the alarm thread if it is not busy(
* that is, if current alarm is 0, signifying that it's waiting for work),
* or if the new alarm comes before the one on which the alarm thread is waiting.
*/
if (current_alarm == || alarm->time < current_alarm) {
current_alarm = alarm->time;
status = pthread_cond_signal(&alarm_cond);
if (status != )
err_abort(status, "Signal cond");
}
} void *alarm_thread(void* arg)
{
alarm_t* alarm;
struct timespec cond_time;
time_t now;
int status, expired; /*
* loop forever, processing commands.
* the alarm thread will be disintegrated when the process exits.
* lock the mutex at the start -- it while be unlocked during condi
* -tion waits, so the main thread can insert alarms.
*/
status = pthread_mutex_lock(&alarm_mutex);
if (status != )
err_abort(status, "Lock mutex");
while () {
/*
* if the alarm list is enpty, wait until an alarm is added.
* setting current_alarm to 0 informs the insert routine that
* the trhead is not busy.
*/
current_alarm = ;
while (alarm_list == NULL) {
status = pthread_cond_wait(&alarm_cond, &alarm_mutex);
if (status != )
err_abort(status, "wait on cond");
}
alarm = alarm_list;
alarm_list = alarm->link;
now = time(NULL);
expired = ;
if (alarm->time > now) {
#ifdef DEBUG
printf("[waiting: %d(%d)\"%s\"]\n",alarm->time,
alarm->time - time(NULL), alarm->message);
#endif
cond_time.tv_sec = alarm->time;
cond_time.tv_nsec = ;
current_alarm = alarm->time;
while (current_alarm == alarm->time) {
status = pthread_cond_timedwait(
&alarm_cond, &alarm_mutex, &cond_time);
if (status == ETIMEDOUT) {
expired = ;
break;
}
if (status != )
err_abort(status, "cond timedwait");
}
if (!expired)
alarm_insert(alarm);
}
else
expired = ;
if (expired) {
printf("(%d) %s\n", alarm->seconds, alarm->message);
free(alarm);
}
} } int main(int argc, char* argv[])
{
int status;
char line[];
alarm_t *alarm;
pthread_t thread; status = pthread_create(
&thread, NULL, alarm_thread, NULL);
if (status != )
err_abort(status, "create alarm thread");
while () {
printf("Alarm> ");
if (fgets(line, sizeof(line), stdin) == NULL) exit();
if (strlen(line) <= ) continue;
alarm = (alarm_t*)malloc(sizeof(alarm_t));
if (alarm == NULL)
errno_abort("Allocate alarm"); if (sscanf(line, "%d %64[^\n]", &alarm->seconds, alarm->message) < ) {
fprintf(stderr, "Bad command\n");
free(alarm);
} else {
status = pthread_mutex_lock(&alarm_mutex);
if (status != )
err_abort(status, "Lock mutex");
alarm->time = time(NULL) + alarm->seconds; alarm_insert(alarm);
status = pthread_mutex_unlock(&alarm_mutex);
if (status != )
err_abort(status, "Unlock mutex");
}
}
}
alarm_cond.c
posix thread条件变量的更多相关文章
- Linux Qt使用POSIX多线程条件变量、互斥锁(量)
今天团建,但是文章也要写.酒要喝好,文要写美,方为我辈程序员的全才之路.嘎嘎 之前一直在看POSIX的多线程编程,上个周末结合自己的理解,写了一个基于Qt的用条件变量同步线程的例子.故此来和大家一起分 ...
- posix多线程--条件变量
条件变量是用来通知共享数据状态信息的. 1.条件变量初始化两种方式:(1)静态初始化pthread_cond_t cond = PTHREAD_COND_INITIALIZER;代码示例如下: #in ...
- Linux Posix线程条件变量
生产者消费者模型 .多个线程操作全局变量n,需要做成临界区(要加锁--线程锁或者信号量) .调用函数pthread_cond_wait(&g_cond,&g_mutex)让这个线程锁在 ...
- 并发编程(一): POSIX 使用互斥量和条件变量实现生产者/消费者问题
boost的mutex,condition_variable非常好用.但是在Linux上,boost实际上做的是对pthread_mutex_t和pthread_cond_t的一系列的封装.因此通过对 ...
- Linux多线程实践(8) --Posix条件变量解决生产者消费者问题
Posix条件变量 int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr); int pthread_co ...
- posix 条件变量与互斥锁 示例生产者--消费者问题
一.posix 条件变量 一种线程间同步的情形:线程A需要等某个条件成立才能继续往下执行,现在这个条件不成立,线程A就阻塞等待,而线程B在执行过程中使这个条件成立了,就唤醒线程A继续执行. 在pthr ...
- POSIX 使用互斥量和条件变量实现生产者/消费者问题
boost的mutex,condition_variable非常好用.但是在Linux上,boost实际上做的是对pthread_mutex_t 和pthread_cond_t的一系列的封装.因此通过 ...
- 并发编程入门(一): POSIX 使用互斥量和条件变量实现生产者/消费者问题
boost的mutex,condition_variable非常好用.但是在Linux上,boost实际上做的是对pthread_mutex_t和pthread_cond_t的一系列的封装.因此通过对 ...
- linux Posix线程同步(条件变量) 实例
条件变量:与互斥量一起使用,暂时申请不到某资源时进入条件阻塞等待,当资源具备时线程恢复运行 应用场合:生产线程不断的生产资源,并通知产生资源的条件,消费线程在没有资源情况下进入条件等待,一直等到条件信 ...
随机推荐
- LeetCode题解——Median of Two Sorted Arrays
题目: 找两个排序数组A[m]和B[n]的中位数,时间复杂度为O(log(m+n)). 解法: 更泛化的,可以找第k个数,然后返回k=(m+n)/2时的值. 代码: class Solution { ...
- 数电课设——琐碎
这几天没有更新过网站了,也没继续开发VellLock了,可是感觉还是没有闲着,一直在跟下面的一些元器件在打交道,当然下面的都是小儿科,英文文档都看得我快吐血了.数电基本属于棺材边上过的我,是各种头大, ...
- 【转载】高性能I/O设计模式Reactor和Proactor
转载自:http://blog.csdn.net/roger_77/article/details/1555170 昨天购买了<程序员>杂志 2007.4期,第一时间去翻阅了一遍,其中有一 ...
- HDU-4696 Answers 纯YY
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4696 题意:给一个图,每个点的出度为1,每个点的权值为1或者2.给n个询问,问是否能找到一条路径的权值 ...
- jitsi-meet
Jitsi Meet在Ubuntu上的快速安装与卸载 1. 进入到终端,切换到root用户 # sudo su 添加相应的代码仓库: # echo 'deb http://download.jitsi ...
- openstack rc
#!/bin/bash export OS_PROJECT_DOMAIN_ID=default export OS_USER_DOMAIN_ID=default export OS_PROJECT_N ...
- 将NavigationBar设置透明
将NavigationBar设置透明(仅将指定视图控制器进行透明处理),步骤如下:1.在视图控制器的头文件中实现UINavigationControllerDelegate,例如:@interface ...
- 转载SSIS中的容器和数据流—数据转换(Transformations)续
数据挖掘请求 数据挖掘任务是SSIS中一个很重要的任务,它的思想来源于一些算法.数据挖掘请求运行数据挖掘请求,并将结果输出到数据流.它还可以添加一些预测新列,一些应用场合如下列举: 根据已知的一些列, ...
- 5A的肖特基二极管 SK5x / SK5xx
5A的肖特基 管压降经实测2A/0.3V, SK5x 和SK5xx别在于前者是四位命名,后者是一个五位命名带B, 封装不一样,参数基本一致.不细看手册容易用错了. 四位命名:封装为SMC (DO-21 ...
- Android模拟器访问本地的apache tomcat服务
1. 在官网http://tomcat.apache.org/上下载tomcat,根据自己的电脑下载相应的文件 2.将apache-tomcat-6.0.37-windows-x64.zip包解压到本 ...