1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include <time.h>
int ticket = 1;
pthread_mutex_t booked; pthread_mutex_t called;
sem_t sites; sem_t person;
typedef struct ListNode{ int val; struct ListNode * next; }Node;
struct ListNode* head; struct ListNode* tail;
void* passerby(void * arg){ srand((unsigned)time( NULL )); while(1){
sem_wait(&sites); pthread_mutex_lock(&booked); Node* newNode = (Node*)malloc(sizeof(Node));
int val = 0; sem_getvalue(&sites,&val); printf("%ld 顾客正在叫号:%d, 剩余位置:%d\n",pthread_self(),ticket,val);
newNode->val = ticket++; newNode->next = NULL; tail->next = newNode; tail = newNode; pthread_mutex_unlock(&booked); sem_post(&person); int waitnum = rand()% 10; sleep(waitnum); } return NULL; }
void* server(void* arg){ srand((unsigned)time( NULL )); while(1){ sem_wait(&person); pthread_mutex_lock(&called); Node* tmp = head->next; if(tmp == tail){ tail = head; }
int val = 0; sem_getvalue(&person,&val);
printf("%ld 正在服务 %d 号顾客, 剩余顾客%d \n",pthread_self(),tmp->val,val); head->next = tmp->next; free(tmp); pthread_mutex_unlock(&called); sem_post(&sites); int sleeptime = rand()%20; sleep(sleeptime); } return NULL; }
int main(){
pthread_mutex_init(&called,NULL); pthread_mutex_init(&booked,NULL); sem_init(&sites,0,10); sem_init(&person,0,0);
head = (Node *)malloc(sizeof(Node)); head->next = NULL; tail = head;
pthread_t sertid[2],pastid[2]; for(int i=0;i<2;i++){ pthread_create(&sertid[i],NULL,server,NULL); pthread_create(&pastid[i],NULL,passerby,NULL); }
for(int i=0;i<2;i++){ pthread_join(sertid[i],NULL); pthread_join(pastid[i],NULL); }
pthread_mutex_destroy(&booked); pthread_mutex_destroy(&called);
pthread_exit(NULL);
return 0; }
|