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线程同步(条件变量) 实例
条件变量:与互斥量一起使用,暂时申请不到某资源时进入条件阻塞等待,当资源具备时线程恢复运行 应用场合:生产线程不断的生产资源,并通知产生资源的条件,消费线程在没有资源情况下进入条件等待,一直等到条件信 ...
随机推荐
- 黑盒测试用例设计方法&理论结合实际 -> 边界值分析法
一. 概念 边界值分析法就是对输入或输出的边界值进行测试的一种黑盒测试方法.通常边界值分析法是作为对等价类划分法的补充,这种情况下,其测试用例来自等价类的边界. 二. 边界值分析法的应用 根据大量的测 ...
- minicom 没有tx 信号
在minicom -s 的配置中:——> Serial port setup --> 选择F - Hardware Flow Control : No默认是yes, 但是没有tx信号输出 ...
- matlab 函数说明—ordfilt2
今天看harris角点实现的源码,在某一个版本中看到了这个函数,不是很理解,doc ordfilt2之后还是不清楚,终于在matlab论坛上搞清楚了ordfilt2的功能. 中文理解函数名就是顺序 ...
- 50道经典的JAVA编程题(46-50)
50道经典的JAVA编程题(46-50),最后五道题了,这是一个美妙的过程,编程真的能让我忘掉一切投入其中,感觉很棒.今天下午考完微机原理了,大三上学期就这样度过了,这学期算是解放了,可是感觉我还是没 ...
- HW6.24
public class Solution { public static void main(String[] args) { int count = 0; int color; int numbe ...
- dataStructure@ Check whether a given graph is Bipartite or not
Check whether a given graph is Bipartite or not A Bipartite Graph is a graph whose vertices can be d ...
- 【noip2007】树网的核
题解: 首先我们要知道一个性质:如果有多条直径 这个核不论在哪条直径上 答案都是一样的 这样我们就可以随便找一条直径 在这条直径上枚举核的位置 并且dfs预处理maxlon[i] (i在直径上) 表示 ...
- cdh4
libhadoop.so其实是后面安装impala时要用到 此处配置环境变啦时注意 下 export CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/l ...
- poj 3250 Bad Hair Day【栈】
Bad Hair Day Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 15922 Accepted: 5374 Des ...
- 在多线程中进行UI操作
那么在子线程中的UI操作如何处理呢?有两种方法: 一:在子线程,你需要进行的UI操作前添加dispatch_async函数,即可将代码块中的工作转回到主线程 dispatch_async(dispat ...