posix 条件变量的使用

条件变量是对全局变量使用的同步机制,一个线程等待条件的成立,另一个线程适当时使条件成立。

条件变量的使用很容易造成等待的线程一直休眠下去,要保证等待条件成立的线程在最后一次成立后能结束。

可以将条件变量理解成一种全局变量。对它使用时总是先加互斥锁。

pthread_cond_t cond 定义了cond的条件变量。

初始化有两种方式:静态的和动态的。

静态的初始化用PTHREAD_COND_INITIALIZER。

动态的初始化则使用pthread_cond_init(&cond, NULL); 第二个参数表示cond的属性,linux没有实现,所以设为NULL

销毁用pthread_cond_destroy(&cond)

等待操作:

pthread_mutex_lock (&mutex)

pthread_cond_wait (&cond, &mutex)

pthread_mutex_unlock (&mutex)

使条件成立:

pthread_mutex_lock (&mutex)

pthread_cond_signal (&cond)

pthread_mutex_unlock (&mutex)

其中,pthread_cond_wait (&cond, &mutex) 里面有两种操作

1,解锁mutex

2,休眠在cond上等待被唤醒。

所有操作函数参数都是指针类型。

实例:

两个线程,遍历1~9个数,一个将不是3的倍数的数输出,另一个线程输出3的倍数。

显然3的倍数的数相对少些,可以让一个线程等待这个条件的发生。而另一线程去遍历1~9个数,当遍历到3的倍数时使相应条件成立。

如果下面程序线程一中,改为for (i = 1; i < 9; i ++),那么线程二将一直等待条件,而不会结束。

实现如下:

View Code
View Code 

include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>


static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int i;

void * pthread_one (void *)
{

    for (i = 1; i <= 9; i ++) 
    {   
        if (i % 3)
        {   
            std::cout << "pthread_one " ": " << i << std::endl;
        }   

        else
        {   
            pthread_mutex_lock (&mutex);
    
            pthread_cond_signal (&cond);

            pthread_mutex_unlock (&mutex);
        }   
        sleep (1);
    }   


}

void * pthread_two (void * ) 
{

    while (i < 9)
    {   

        if (i % 3)
        {   
            pthread_mutex_lock (&mutex);

            pthread_cond_wait (&cond, &mutex);

            pthread_mutex_unlock (&mutex);
        }   

        std::cout << "pthread_two " ": " << i << std:: endl;
        sleep (1);
    }   
}

int main()
{
    pthread_t pthread_1;
    pthread_t pthread_2;

    pthread_create (&pthread_1, NULL, pthread_one, NULL);
    pthread_create (&pthread_2, NULL, pthread_two, NULL);

    pthread_join (pthread_1, NULL);
    pthread_join (pthread_2, NULL);

    exit (0);
}

 

输出:

 

 

posted @ 2013-03-01 19:42  lc_cnblog  阅读(675)  评论(0编辑  收藏  举报