linux下多线程编程问题收集

3 篇文章 0 订阅

如果引用了pthread.h头文件,则在链接程序的时候要加上-lpthread选项(g++ -o -lpthread),如:

       //test.cpp

      1 #include<iostream>
      2
      3 #include<pthread.h>
      4 #include<unistd.h>
      5
      6 using namespace std;
      7
      8 int kk = 0;
      9
     10 void* fun(void *p)
     11 {
     12         cout<<"a new thread"<<endl;
     13
     14         int count = 100;
     15         while(count > 0)
     16         {
     17                 kk++;
     18                 cout<<"this is  new thread and kk="<<kk<<endl;
     19
     20                 usleep(1000);
     21                 --count;
     22         }
     23
     24         return p;
     25 }
     26
     27 int main()
     28 {
     29         pthread_t pt;
     30
     31         int ret = pthread_create(&pt,NULL,fun,NULL);
     32
     33         cout<<"ret = "<<ret<<endl;
     34         if(ret != 0)
     35         {
     36                 cout<<"create thread error"<<endl;
     37                 //exit(1);
     38                 return 1;
     39         }
     40
     41
     42         int count = 100;
     43         while(count > 0)
     44         {
     45                 kk += 2;
     46                 cout<<"this is main thread and kk="<<kk<<endl;
     47                 usleep(1000);
     48                 --count;
     49         }
     50
     51
     52         pthread_join(pt,NULL);
     53
     54         return 0;
     55
     56 }

 

则编译该文件的Makefile可以写成:

      //makefile

      1 test.exe:test.o
      2         g++ -o test.exe -lpthread test.o
      3
      4 test.o:test.cpp
      5         g++ -c test.cpp

注意其中的-lpthread不要漏了,否则会链接出错。

-lpthread编译(应该是链接吧?)选项的作用是链接多线程的库.
在程序中用到了pthread.h头文件中的函数时需要加这个选项.

 

-lpthread,不应该加在编译参数里面,而应该加在链接里面,把所有.o文件链接成可执行文件时候,加这个动态库。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值