Chinaunix首页 | 论坛 | 博客
  • 博客访问: 61019
  • 博文数量: 26
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 255
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-18 10:40
文章分类

全部博文(26)

文章存档

2013年(26)

我的朋友

分类: LINUX

2013-10-10 15:37:16

条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起


条件变量需要与互斥变量配合使用,其中pthread_cond_wait(),需要互斥量锁住,以防多个线程发出等待要求。
且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。   流程为block -> unblock(阻塞在等待队列休眠)-> (条件满足)block先锁住在读资源wait()return ->unblock

一下模型可以做为一个生产着和消费者模型的实现

#include
#include
#include
#include
#include
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
struct node
{
    int number;
    struct node *next;
}*head=NULL;
static void clean_handler(void *arg)
{
    free(arg);
    (void)pthread_mutex_unlock(&mutex);
}
static void *ph_tr(void *arg)
{
    struct node *p=NULL;
    pthread_cleanup_push(clean_handler,p);
    while(1)
    {
        pthread_mutex_lock(&mutex);
        while(head==NULL)
        {
            pthread_cond_wait(&cond,&mutex);
        }
        p=head;
        head=head->next;
        printf("number=%d\n",p->number);
        free(p);
        pthread_mutex_unlock(&mutex);
    }
    pthread_cleanup_pop(0);
    return 0;
}
int main(void)
{
    int i=0,n=10;
    struct node *p;
    pthread_t tid;
    pthread_create(&tid,NULL,ph_tr,NULL);
    //printf("pthread_create error");
    for(i;i     {
        p=malloc(sizeof(struct node));
        p->number=i;
        pthread_mutex_lock(&mutex);


        p->next=head;
        head=p;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
         sleep(1);
    }
    pthread_cancel(tid);
    pthread_join(tid,NULL);
    return 0;
}

阅读(1664) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~