Linux環境下C語言線程創建---簡單代碼


在Linux環境下用C語言編寫線程創建。

 1 //file name: pthreadtext.c
 2 
 3 #include <stdio.h>
 4 #include <pthread.h> //線程頭文件  
 5 //pthread不是linux下的默認的庫,也就是在鏈接的時候,無法找到phread庫中哥函數的入口地址,於是鏈接會失敗 
 6 //在gcc編譯的時候,附加要加 -lpthread參數即可解決。gcc -o run pthreadtext.c  -lpthread
 7 
 8 void *myThread1(void) //線程函數
 9 {
10     int i;
11     for(i=0;i<5; i++)
12     {
13         printf("This is the 1st pthread \n");
14         sleep(1);
15     }    
16 }
17 
18 void *myThread2(void)
19 {
20     int i;
21     for(i=0;i<5;i++)
22     {
23         printf("this is the 2st \n");
24         sleep(1);
25     }
26 }
27 
28 int main()
29 {
30     int i=0,ret=0;
31     pthread_t id1,id2;
32     ret= pthread_create(&id1,NULL,(void*)myThread1,NULL ); //創建線程
33     if(ret)
34     {
35         printf("create error\n");
36         return 1;
37     }
38     ret = pthread_create(&id2,NULL,(void*)myThread2,NULL); //創建線程
39     if(ret)
40     {
41         printf("create error\n");
42         return 1;
43     }
44     
45     pthread_join(id1,NULL); //當前線程會處於阻塞狀態,直到被調用的線程結束后,當前線程才會重新開始執行
46     pthread_join(id2,NULL);
47     return 0;
48 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM