多執行緒不重複售票系統
/*====================================================
- Copyright © 2018 All rights reserved.
- 檔名稱:sell_train_ticket.c
- 建立日期:2018年07月27日
- 描 述: ================================================================*/
#include <stdio.h> #include “head.h”
int j = 0; sem_t sem1,sem2,sem3,sem4,sem5; //宣告訊號量
void *fun1(void * arg) { int i =0,*tmp = 0; int *n = &j; int *str = (int *)arg; while(1) { int ret = sem_trywait(&sem1); //按給定有效值1來順序執行 if(ret == 0) { if(*n > 99) { sem_post(&sem2);//釋放訊號並給下一個 pthread_exit(0); } printf(“一視窗售號為: %d \n”,str[*n]); (*n)++; sem_post(&sem2); } else { // sleep(1); }
}
} void *fun2(void * arg) { int i =0; int *n = &j; int *str = (int *)arg; while(1) { int ret = sem_trywait(&sem2); if(ret == 0) { if(*n > 99) { sem_post(&sem3); pthread_exit(0); } printf(“二視窗售號為: %d \n”,str[*n]); (*n)++; sem_post(&sem3); } else { // sleep(1); } } } void *fun3(void * arg) { int i =0,*tmp = 0; int *n = &j; int *str = (int *)arg; while(1) { int ret = sem_trywait(&sem3); if(ret == 0) { if(*n > 99) { sem_post(&sem4); pthread_exit(0); } printf(“三視窗售號為: %d \n”,str[*n]); (*n)++; sem_post(&sem4); } else { // sleep(1); } } } void *fun4(void * arg) { int i =0; int *n = &j; int *str = (int *)arg; while(1) { int ret = sem_trywait(&sem4); if(ret == 0) { if(*n > 99) { sem_post(&sem5); pthread_exit(0); } printf(“四視窗售號為: %d \n”,str[*n]); (*n)++; sem_post(&sem5); } else { // sleep(1); } } } void *fun5(void * arg) { int i =0,*tmp = 0; int *n = &j; int *str = (int *)arg; while(1) { int ret = sem_trywait(&sem5); if(ret == 0) { if(*n > 99) { sem_post(&sem1); pthread_exit(0); } printf(“五視窗售號為: %d \n”,str[*n]); (*n)++; sem_post(&sem1); } else { // sleep(1); } } } int main(int argc, char *argv[]) { int buff[100] = {0},i = 0,p = 1; for(i=0;i<100;i++) { buff[i] = p; p++; } sem_init(&sem1,0,1); //初始化訊號量 sem_init(&sem2,0,0); sem_init(&sem3,0,0); sem_init(&sem4,0,0); sem_init(&sem5,0,0); pthread_t tid1 = 0,tid2 = 0,tid3 = 0,tid4 = 0,tid5 = 0;//初始化執行緒 pthread_create(&tid1,NULL,fun1,(void *)buff);//執行緒的建立 pthread_create(&tid2,NULL,fun2,(void *)buff); pthread_create(&tid3,NULL,fun3,(void *)buff); pthread_create(&tid4,NULL,fun4,(void *)buff); pthread_create(&tid5,NULL,fun5,(void *)buff); pthread_join(tid1,NULL); //執行緒的回收 pthread_join(tid2,NULL); pthread_join(tid3,NULL); pthread_join(tid4,NULL); pthread_join(tid5,NULL); return 0; }