Chinaunix首页 | 论坛 | 博客
  • 博客访问: 803310
  • 博文数量: 869
  • 博客积分: 201
  • 博客等级: 入伍新兵
  • 技术积分: 3376
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-21 19:42
文章分类

全部博文(869)

文章存档

2014年(4)

2013年(415)

2012年(453)

我的朋友

分类:

2012-12-03 11:13: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;
}


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