现在的位置: 首页 > 综合 > 正文

1.6 线程同步–条件变量

2014年02月28日 ⁄ 综合 ⁄ 共 1770字 ⁄ 字号 评论关闭

目录

一.函数

1.条件变量的初始化与销毁:
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond,
                                          pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);

Both return: 0 if OK, error number on failure
2.等待条件信号:
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond,
                                            pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
                                                      pthread_mutex_t *restrict mutex,
                                                      const struct timespec *restrict timeout); 

Both return: 0 if OK, error number on failure
3.发送条件信号:
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

Both return: 0 if OK, error number on failure
二.重点:
1.如果条件变量是静态分配的,初始化可以直接赋值:PTHREAD_COND_INITIALIZER。
三.例子:
注意,缺少错误检查

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  gcond  = PTHREAD_COND_INITIALIZER;
int  count = 0;

void *thr_fn1()
{
    while(1)
    {
        pthread_mutex_lock( &gmutex );
        pthread_cond_wait( &gcond, &gmutex );
        count++;
        printf("thr_fn1,count: %d\n",count);
        pthread_mutex_unlock( &gmutex );
        if(count >= 10)
            return NULL;
    }
}

void *thr_fn2()
{
    while(1)
    {
        pthread_mutex_lock( &gmutex );
        if( count < 3 || count > 6 )
        {
            pthread_cond_signal( &gcond );
        }
        else
        {
            count++;
            printf("thr_fn2,count: %d\n",count);
        }
        pthread_mutex_unlock( &gmutex );
        if(count >= 10)
            return NULL;
    }
}

int main()
{
    pthread_t thread1, thread2;

    pthread_create( &thread1, NULL, &thr_fn1, NULL);
    pthread_create( &thread2, NULL, &thr_fn2, NULL);

    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);

    printf("Final count: %d\n",count);
    return 0;
}

运行:
root@ubuntu1:~/11# ./a.out
thr_fn1,count: 1
thr_fn1,count: 2
thr_fn1,count: 3
thr_fn2,count: 4
thr_fn2,count: 5
thr_fn2,count: 6
thr_fn2,count: 7
thr_fn1,count: 8
thr_fn1,count: 9
thr_fn1,count: 10
Final count: 10
root@ubuntu1:~/11#

抱歉!评论已关闭.