linux网络编程-线程创建和退出

线程创建函数:int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); 第一个参数thread是出参,传出创建的线程id;第二个参数attr是线程属性,可以不设置,传入NULL即可;第三个参数start_routine是用户定义的函数,也就是线程要执行的函数;arg是传给start_routine的参数,不需要参数时传入NULL即可;线程创建函数执行成功时返回0,返回其他值则存在错误。

线程终止:线程有多种情况会发生终止,1) 线程内调用pthread_exit,2) start_routine自己返回,3) 线程被cancel(pthread_cancel),4) 进程通过exit终止。

线程退出函数:int pthread_cancel(pthread_t thread); 该函数根据参数(线程id),给指定线程发送退出信号。

举个例子:消费者线程给生产者线程发送退出信号。

 1 //由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数
 2 //gcc pthread_cancel.c -lpthread -o pthread
 3 #include <stdio.h>
 4 #include <sched.h>
 5 #include <pthread.h>
 6 
 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 int count = 0;
13 
14 pthread_t consumer_t;
15 pthread_t producter_t;
16 
17 int main(void)
18 {
19 
20     pthread_mutex_init(&mutex, NULL);
21     pthread_create(&producter_t, NULL, (void*)producter_f, NULL);
22     pthread_create(&consumer_t, NULL, (void*)consumer_f, NULL);
23 
24     sleep(5);
25     //running = 0;
26     
27 
28     pthread_join(consumer_t, NULL);
29     printf("consumer退出\n");
30     pthread_join(producter_t, NULL);
31     printf("producter退出\n");
32     pthread_mutex_destroy(&mutex);
33 }
34 
35 void *producter_f(void *arg)
36 {
37     while(running)
38     {
39         //pthread_mutex_lock(&mutex);
40         printf("生产前,总数量:%d\n", buffer_has_item);
41         buffer_has_item++;
42         printf("生产后,总数量:%d\n", buffer_has_item);
43         //pthread_mutex_unlock(&mutex);
44         sleep(1);
45     }
46 }
47 
48 void *consumer_f(void *arg)
49 {
50     while(running)
51     {
52         //pthread_mutex_lock(&mutex);
53         printf("消费前,总数量:%d\n", buffer_has_item);
54         buffer_has_item--;
55         count++;
56         printf("消费后,总数量:%d, count = %d\n", buffer_has_item, count);
57         //将生产者退出
58         if(count > 5) pthread_cancel(producter_t);
59         //pthread_mutex_unlock(&mutex);
60         sleep(1);
61     }
62 }

编译:

gcc pthread_cancel.c -lpthread -o pthread

运行结果:

$ ./pthread
消费前,总数量:0
消费后,总数量:-1, count = 1
生产前,总数量:0
生产后,总数量:0
消费前,总数量:0
消费后,总数量:-1, count = 2
生产前,总数量:0
生产后,总数量:0
消费前,总数量:0
消费后,总数量:-1, count = 3
生产前,总数量:-1
生产后,总数量:0
消费前,总数量:0
消费后,总数量:-1, count = 4
生产前,总数量:0
生产后,总数量:0
消费前,总数量:0
消费后,总数量:-1, count = 5
生产前,总数量:-1
生产后,总数量:0
消费前,总数量:0
消费后,总数量:-1, count = 6
生产前,总数量:0
生产后,总数量:0
consumer退出
生产前,总数量:0
生产后,总数量:1
生产前,总数量:1
生产后,总数量:2
生产前,总数量:2
生产后,总数量:3
生产前,总数量:3
生产后,总数量:4
生产前,总数量:4
生产后,总数量:5
生产前,总数量:5

 

posted @ 2022-12-25 10:58  Parker_Zhou  阅读(233)  评论(0)    收藏  举报