1 //由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数 2 //gcc pthread_sig_mutex.c -lpthread -D_GNU_SOURCE -o pthread 3 #include <stdio.h> 4 #include <signal.h> 5 #include <sched.h> 6 #include <pthread.h> 7 void *producter_f(void *arg); 8 void *consumer_f(void *arg); 9 int buffer_has_item = 0; 10 pthread_mutex_t mutex; 11 int running = 1; 12 13 static void sig_handle(int signo) 14 { 15 switch(signo) 16 { 17 case SIGTERM: 18 printf("收到信号SIGTERM, value = %d\n", signo); 19 //释放锁 20 pthread_mutex_unlock(&mutex); 21 break; 22 23 default: 24 printf("收到其他信号,value=%d\n", signo); 25 break; 26 } 27 return; 28 } 29 30 int main(void) 31 { 32 pthread_t consumer_t; 33 pthread_t producter_t; 34 pthread_mutex_init(&mutex, NULL); 35 pthread_create(&producter_t, NULL, (void*)producter_f, NULL); 36 pthread_create(&consumer_t, NULL, (void*)consumer_f, NULL); 37 38 sighandler_t ret; 39 ret = signal(SIGTERM, sig_handle); 40 if(SIG_ERR==ret) 41 { 42 printf("为SIGTERM挂接信号处理函数失败\n"); 43 return -1; 44 } 45 printf("开始监听信号...\n"); 46 47 48 49 //等待线程结束 50 pthread_join(consumer_t, NULL); 51 pthread_join(producter_t, NULL); 52 53 pthread_mutex_destroy(&mutex); 54 } 55 56 void *producter_f(void *arg) 57 { 58 while(running) 59 { 60 pthread_mutex_lock(&mutex); 61 printf("生产前,总数量:%d\n", buffer_has_item); 62 buffer_has_item++; 63 printf("生产后,总数量:%d\n", buffer_has_item); 64 //pthread_mutex_unlock(&mutex); 65 sleep(1); 66 } 67 } 68 69 void *consumer_f(void *arg) 70 { 71 while(running) 72 { 73 pthread_mutex_lock(&mutex); 74 printf("消费前,总数量:%d\n", buffer_has_item); 75 buffer_has_item--; 76 printf("消费后,总数量:%d\n", buffer_has_item); 77 //pthread_mutex_unlock(&mutex); 78 sleep(1); 79 } 80 }
编译:gcc pthread_sig_mutex.c -lpthread -D_GNU_SOURCE -o pthread
执行:./pthread
测试:打开新终端,执行pkill -15 pthread
结果:
$ ./pthread
开始监听信号...
消费前,总数量:0
消费后,总数量:-1
收到信号SIGTERM, value = 15
生产前,总数量:-1
生产后,总数量:0
收到信号SIGTERM, value = 15
消费前,总数量:0
消费后,总数量:-1
收到信号SIGTERM, value = 15
生产前,总数量:-1
生产后,总数量:0
收到信号SIGTERM, value = 15
消费前,总数量:0
消费后,总数量:-1
收到信号SIGTERM, value = 15
生产前,总数量:-1
生产后,总数量:0