Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47073
  • 博文数量: 33
  • 博客积分: 1301
  • 博客等级: 中尉
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 21:06
文章分类
文章存档

2009年(33)

我的朋友

分类:

2009-07-01 22:14:30

 

司机和售票员的经典信号量例子。

semaphore close = 0, stop = 1;

driver(){
    P(close);
    启动
    开车
    停车
    V(stop);
}

seller(){
    P(stop);
    开门,乘客上下车,关门
    V(close);
    售票
}

 
 
 
为了好看点,线程函数为f1,f2,处理信号量的为driver和seller
 

#define _REENTRANT

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

void *f1(void *), *f2(void *);

sem_t s_c, s_s;

int main() {
    pthread_t t1;
    int res;

    sem_init(&s_c, 0, 0);
    sem_init(&s_s, 0, 1);
    
    res = pthread_create(&t1, NULL, f2, NULL);
    if(res != 0) {
        fprintf(stderr, "pthread_create failed.\n");
        return -1;
    }

    f1(NULL);

    res = pthread_join(t1, NULL);
    if(res != 0) {
        fprintf(stderr, "pthread_join failed.\n");
        return -1;
    }
    return 0;
}

void driver() {
    while(1) {
        sem_wait(&s_c);
        printf("Driver: boot up\n");
        sleep(1);
        printf("Driver: drive\n");
        sleep(5);
        printf("Driver: stop\n");
        sleep(1);
        sem_post(&s_s);
    }
}

void seller() {
    while(1) {
        sem_wait(&s_s);
        printf("Seller: open door\n");
        sleep(1);
        printf("Seller: let in and out\n");
        sleep(2);
        printf("Seller: close door\n");
        sleep(1);
        sem_post(&s_c);
        printf("Seller: Sell.\n");
        sleep(3);
    }
}

void *f1(void *arg) {
    driver();
    return NULL;
}

void *f2(void *arg) {
    seller();
    pthread_exit(NULL);
}

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