牛刀小试:售票系统
功能:询问是否购票,输入y/Y表示购票,输入其他字符表示不购票,跳转到退票功能。退票功能输入Y/y退票,输入其他字符再跳转到购票功能。让用户在购票和退票功能之间选择。
代码:
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> void *task_sale(void *arg); void *task_add(void *arg); pthread_t tid[2]; pthread_mutex_t lock; int ticket = 5; int main(void) { int ret; pthread_mutex_init(&lock,NULL); pthread_create(&tid[0],NULL,task_sale,(void*)1); pthread_create(&tid[1],NULL,task_add,(void*)2);
pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); pthread_mutex_destroy(&lock); pthread_exit(NULL);
} void *task_sale(void *arg) { char s[1]; printf(“This thread %ld\r\n”,(intptr_t)(int *)arg); while(1) { memset(s,0,sizeof(s)); pthread_mutex_lock(&lock); printf(“现在有余票:%d\r\n”,ticket); if(ticket > 0) { printf(“是否购票?购票请输入Y/y\r\n”); scanf("%s",s); if(strncmp(s,“y”,1)==0) { ticket–; printf(“购票成功,剩余:%d\r\n”,ticket); sleep(1); pthread_mutex_unlock(&lock); } else { pthread_mutex_unlock(&lock); usleep(500); }
} else { printf("没票了还买啥,走路去吧\r\n"); pthread_mutex_unlock(&lock); sleep(2); } } pthread_exit(NULL);
} void *task_add(void *arg) { char a[1]; printf(“这是退票窗口%ld\r\n”,(intptr_t)(int *)arg); while(1) { memset(a,0,sizeof(a)); pthread_mutex_lock(&lock); printf(“现在票仓有票:%d\r\n”,ticket); if(ticket <5 ) { printf(“是否退票?退票请输入Y/y\r\n”); scanf("%s",a); if(strncmp(a,“y”,1)==0) { ticket++; printf(“退票成功,剩余:%d\r\n”,ticket); //system(“clear”); sleep(1); pthread_mutex_unlock(&lock);
} else { //printf("不退凑啥热闹\r\n"); //system("clear"); pthread_mutex_unlock(&lock); usleep(500); } } else { printf("你都没买你退啥,玩儿呢?\r\n"); pthread_mutex_unlock(&lock); sleep(1); } } pthread_exit(NULL);
}
效果: