Ubuntu下多线程简单的线程锁抢门票问题(C语言)
该小程序创建了4个线程作为窗口进行演示抢票,程序中简单的使用pthread_mutex_lock与pthread_mutex_unlock:
main.c:
1 #include<stdio.h> 2 #include<pthread.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<sched.h> 6 #include<unistd.h> 7 #define NUMBER 10 //总票数 8 static int ticket=NUMBER; 9 static int ticket1;//标志,1 有票 0 无票 10 static pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; 11 static void *send(void *arg); 12 int main(void) 13 { 14 pthread_t tid[4]; 15 int err; 16 for(int i=1;i<5;i++){ 17 err=pthread_create(tid+i-1,NULL,send,(void *)i); 18 if(err){ 19 fprintf(stderr,"pthread_create() %s \n",strerror(err)); 20 exit(1); 21 } 22 } 23 //for(int i=0;i<5;i++) 24 // pthread_detach(tid[0]); 25 pthread_mutex_lock(&mut); 26 while(ticket){ 27 ticket1=1; 28 pthread_mutex_unlock(&mut); 29 sched_yield(); 30 pthread_mutex_lock(&mut); 31 ticket--; 32 } 33 pthread_mutex_unlock(&mut); 34 35 36 for(int i=0;i<4;i++){ 37 pthread_join(tid[i],NULL); 38 } 39 40 exit(0); 41 42 } 43 static void *send(void *arg){ 44 int a=(int)arg;//接收窗口编号 45 46 pthread_mutex_lock(&mut); 47 while(ticket){ 48 while(!ticket1){ 49 pthread_mutex_unlock(&mut); 50 sched_yield(); //这步不需要,本窗口卖出可以继续卖 51 pthread_mutex_lock(&mut); 52 if(ticket==0) 53 goto ER; 54 } 55 ticket1=0; 56 sleep(1); 57 printf("窗口[%d]卖出了No.[%d]演唱会门票\n",a,NUMBER-ticket+1); 58 // pthread_mutex_unlock(&mut); 59 60 } 61 pthread_mutex_unlock(&mut); 62 pthread_exit((void *)0); 63 ER: 64 pthread_mutex_unlock(&mut); 65 pthread_exit((void *)0); 66 }
编译:
(警告正常,int类型与void*转化)
zj@zj-pc:~/6.dir/3-29.c/ticket$ gcc ticket.c -pthread ticket.c: In function ‘main’: ticket.c:17:40: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] err=pthread_create(tid+i-1,NULL,send,(void *)i); ^ ticket.c: In function ‘send’: ticket.c:44:8: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] int a=(int)arg;
结果:
zj@zj-pc:~/6.dir/3-29.c/ticket$ ./a.out 窗口[2]卖出了No.[1]演唱会门票 窗口[1]卖出了No.[2]演唱会门票 窗口[1]卖出了No.[3]演唱会门票 窗口[4]卖出了No.[4]演唱会门票 窗口[4]卖出了No.[5]演唱会门票 窗口[4]卖出了No.[6]演唱会门票 窗口[4]卖出了No.[7]演唱会门票 窗口[1]卖出了No.[8]演唱会门票 窗口[1]卖出了No.[9]演唱会门票 窗口[2]卖出了No.[10]演唱会门票