您的位置:首页 > 其它

利用条件变量实现线程间同步

2013-12-19 20:41 120 查看
 
作者:曾宏安,华清远见嵌入式学院讲师。

我们在编写多线程程序时经常需要在线程之间实现通信,常见的机制有信号量和互斥锁。这里再向大家介绍一种用于实现线程间同步的机制——条件变量。

条件变量可以使线程睡眠等待直到某个条件满足为止。条件变量基本使用操作有两种:一、当判断条件不满足时,某些线程睡眠在相应的条件变量上;二、某些线程改变了条件,唤醒睡眠在条件变量上的其他线程。

为了在判断或是改变条件时防止竞争,条件变量通常和互斥锁结合在一起使用。条件变量类型为pthread_cond_t,互斥锁类型为pthread_mutex_t。

条件变量的创建和注销

int  pthread_cond_init(pthread_cond_t *restrict
cond,pthread_condattr_t *restrict cond_attr); // 创建

cond
: 指向要初始化的条件变量的指针

cond_attr
: 条件变量的初始化属性



pthread_cond_t
cond = PTHREAD_COND_INITIALIZER;

int pthread_cond_destroy(pthread_cond_t *cond); // 注销

条件变量的等待和激活

int pthread_cond_wait(pthread_cond_t *restrict cond,

pthread_mutex_t
*restrict mutex);

该函数使当前线程释放互斥锁mutex并睡眠在条件变量cond上,正确返回时当前线程获得互斥锁mutex

int pthread_cond_timewait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,const struct timespec *restrict
abstime);

该函数功能同pthread_cond_wait,但睡眠时间不超过abstime,正确返回时当前线程获得互斥锁mutex

int pthread_cond_signal(pthread_cond_t *cond);

该函数唤醒等待在条件变量cond上的某个线程

int pthread_cond_broadcast(pthread_cond_t *cond);

该函数唤醒等待在条件变量cond上的所有线程

下面我们看一个例子,了解一下条件变量的用法

#include <stdio.h>

#include
<stdlib.h>

#include
<unistd.h>

#include
<pthread.h>

#define
N 6

pthread_mutex_t
mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t
cond = PTHREAD_COND_INITIALIZER;

void
*thread_function(void *);

int
count = 0;

int
data
;

int
main()

{

pthread_t
thread_a;

int
i;

if
(pthread_create(&thread_a, NULL, thread_function,
NULL) < 0)

{

perror(“fail
to pthread_create”);

exit(-1);

}

while
( 1 )

{

printf(“please
input number : “);

scanf(“%d”,
&i);

if
(i = = 0) break;

pthread_mutex_lock(&mutex);

data[count++]
= i;

if
(count == N) pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

usleep(100000);

}

pthread_mutex_destroy(&mutex);

pthread_cond_destroy(&cond);

return
0;

}

void
*thread_function(void *arg)

{

while
( 1 )

{

int
i, sum;

pthread_mutex_lock(&mutex);

if
(count < N)

{

pthread_cond_wait(&cond,
&mutex);

}

for
(i=0,sum=0; i<N; i++) sum += data[i];

printf(“average
= %d\n”, sum/N);

count
= 0;

pthread_mutex_unlock(&mutex);

}
// end while

return
NULL;

}

在上面的代码中,主线程从键盘读取整数。每读入6个数后,唤醒另外一个线程统计并打印平均数。输入0退出程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: