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 }

 

转载于:https://www.cnblogs.com/mingyue605/p/10060137.html

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值