Linux下编译thread通过,运行时报错'std::system_error' std::thread: Operation not permitted原因及解决办法

16 篇文章 1 订阅

1.出现场景

第一次遇见这个问题是使用thread库做多线程时,

#include <iostream>
#include <thread>
#include <unistd.h>

using namespace std;

void thread1(){
    cout << "thread 01:" << endl;
    for(int i = 0; i < 10; i++){
        cout << "t1:" << i << endl;
    }
}

void thread2(){
    cout << "thread 02:" << endl;
    for(int i = 10; i > 0; i--){
        cout << "t2:" <<  i << endl;
    }
}

int main(int argc, char** argv){

    thread task1(thread1);
    thread task2(thread2);

    task1.join();
    task2.join();

    sleep(1);
    return 0;
}

代码没一点毛病,使用g++编译时,第一次

g++ main.cpp -o thread

结果直接编译报错,

In file included from /usr/local/include/c++/4.9.3/thread:35:0,
                 from main.cpp:2:
/usr/local/include/c++/4.9.3/bits/c++0x_warning.h:32:2: 错误:#error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support for the \
  ^
main.cpp: 在函数‘int main(int, char**)’中:
main.cpp:24:5: 错误:‘thread’在此作用域中尚未声明
     thread task01(thread01);
     ^
main.cpp:25:12: 错误:expected ‘;’ before ‘task02’
     thread task02(thread02);
            ^
main.cpp:27:5: 错误:‘task01’在此作用域中尚未声明
     task01.join();
     ^
main.cpp:28:5: 错误:‘task02’在此作用域中尚未声明
     task02.join();
     ^

这个问题之前遇到比较多,比较老的编译器可能不支持C++11的内容,而thread是c++11里面的,因此重新编译

g++ main.cpp -o thread -std=c++11

结果编译通过,运行时报错

[root@localhost thread]# ./thread 
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
已放弃 (core dumped)

刚开始比较懵逼,去查了一下std::system_error的错误,发现是thread动态库没有链接成功,再次编译

g++ main.cpp -o thread -std=c++11 -lpthread

运行正确。

[root@localhost thread]# ./thread
thread 02:
t2:10
t2:9
t2:8
t2:7
t2:6
t2:5
t2:4
t2:3
t2:2
t2:1
thread 01:
t1:0
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6
t1:7
t1:8
t1:9
2.解决方法

编译时添加-lpthread 或-pthread参数

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值