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