司机和售票员的经典信号量例子。
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); }
|
阅读(1357) | 评论(0) | 转发(0) |