Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1065867
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类:

2009-10-09 14:20:05

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

#define err(msg) perror(msg)

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

static int running = 1;

static void * wait_thread(void *arg)
{
        pthread_mutex_lock(&mutex);
        while (running)
                pthread_cond_wait(&cond, &mutex);
        pthread_mutex_unlock(&mutex);

        printf("receive signal.\n");
}

static void * signal_thread(void *arg)
{
        sleep(3);

        pthread_mutex_lock(&mutex);
        running = 0;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
}

int main(void)
{
        pthread_t t1, t2;

        if (pthread_create(&t1, NULL, wait_thread, NULL) != 0) {
                err("pthread_create");
                goto err;
        }

        if (pthread_create(&t2, NULL, signal_thread, NULL) != 0) {
                err("pthread_create");
                goto err;
        }

        while (running)
                sleep(1);

        return 0;
err:
        return -1;
}


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