首页 > 代码库 > linux多线程互斥-售票
linux多线程互斥-售票
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h>int ticket_cnt = 20; /* 共有20张票 */typedef struct tag{ int s_id; pthread_mutex_t *s_p;}DATA,*pDATA;void* handler(void *arg ){ int id = ((pDATA)arg)->s_id; pthread_mutex_t *p_mutex = ((pDATA)arg)-> s_p; printf("a window on !: %d \n", id); while(1) { pthread_mutex_lock(p_mutex); if(ticket_cnt == 0) { printf("ticket out! \n"); pthread_mutex_unlock(p_mutex); free((pDATA)arg); return (void*)0; } --ticket_cnt; sleep(rand()%3 + 1); printf("window: %d : a ticket sold. left : %d \n", id,ticket_cnt ); pthread_mutex_unlock(p_mutex); sleep(rand() % 3 + 1); /* 如果不sleep,锁会一直被这个执行完的线程所占据 */ }}int main(int argc, char *argv[]){ srand(getpid()); pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL); int thd_cnt = atoi(argv[1]); /* 从命令行输入卖票窗口数 */ pthread_t *tds = (pthread_t*)calloc(thd_cnt,sizeof(pthread_t)); int index; for(index = 0; index < thd_cnt; index++ ) { pDATA p = (pDATA)calloc(1,sizeof(DATA)); p->s_id = index; p->s_p = &mutex; pthread_create(tds + index , NULL,handler,(void*)p); } printf("joining...\n"); for(index = 0; index < thd_cnt; index++) { pthread_join(tds[index],NULL); } pthread_mutex_destroy(&mutex); return 0;}
linux多线程互斥-售票
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。