代码示例_线程

线程

 


1.线程自动分离,常用方法:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 
 5 pthread_mutex_t  mutex;  // 让我们先定义一把 ”锁“ ! 
 6 
 7 
 8 void* fun(void* arg){
 9 
10     pthread_mutex_lock(&mutex);        // 上锁:进行互斥,资源保护 
11     printf("fun : child 1 !
");
12     sleep(1);
13     printf("fun : child 2 !
");
14     sleep(1);
15     printf("fun : child 3 !
");
16     sleep(1);
17     pthread_mutex_unlock(&mutex);  // 解锁:释放
18 
19     pthread_exit(NULL);             // 结束当先线程
20 
21 }
22 
23 
24 int main(void)
25 {
26     
27     pthread_mutex_init(&mutex, NULL);        // 初始互斥锁 
28     
29     pthread_t tid; // 线程 id
30     
31     if( pthread_create(&tid, NULL, fun, NULL) !=0   ){   // 创建线程
32         perror("pthread_creat failed");
33         exit(1);
34     }
35 
36     pthread_detach(tid);                                //  直接分离,自动收尸
37 
38 
39     pthread_mutex_lock(&mutex);        // 上锁:进行互斥,资源保护 
40     printf("main : parent 1 !
");
41     sleep(1);
42     printf("main : parent 2 !
");
43     sleep(1);
44     printf("main : parent 3 !
");
45     sleep(1);
46     pthread_mutex_unlock(&mutex);  // 解锁:释放
47 
48     sleep(5);// 睡眠五秒,不然主进程结束,子线程就jj了,没现象了!!
49    printf("资源互斥,上锁成功 !
");
50     return 0 ;
51 }

2.线程手动分离,用来了解:

 1 void* fun(void* arg){
 2     printf("fun : child !
");
 3     sleep(1);
 4     printf("fun : child !
");
 5     sleep(1);
 6 
 7     printf("先结束线程,再进行收尸
");
 8     pthread_exit(NULL);      // 结束当先线程
 9 
10 }
11 
12 
13 int main(void)
14 {
15     pthread_t tid; // 线程 id
16     
17     if( pthread_create(&tid, NULL, fun, NULL) !=0   ){   // 创建线程
18         perror("pthread_creat failed");
19         exit(1);
20     }
21 
22     printf("main : parent !
");
23     sleep(10);
24 //    printf("main : parent !
");
25 //    sleep(1);
26 
27 
28     if( pthread_join(tid, NULL) !=0 ){            // 给子线程收尸 !   
29         perror("pthread_join  failed");            // 第二个参数为子线程的返回值,自定义!
30         exit(1);
31     }
32     printf("收尸成功
");
33 
34 
35     return 0 ;
36 }

测试:


success !

<笔记>


1. 

Stay hungry, stay foolish 待续。。。
原文地址:https://www.cnblogs.com/panda-w/p/11059617.html