Enable multithreading to use std::thread: Operation not permitted问题解决

在用g++ 4.8.2编译C++11的线程代码后,运行时遇到了如下报错:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)

 

我们先看一下代码:

 1 #include <boost/atomic.hpp>
 2 #include <thread>
 3 #include <iostream>
 4 
 5 boost::atomic<int> a{0};
 6 
 7 void thread()
 8 {
 9   ++a;
10 }
11 
12 int main()
13 {
14   std::thread t1{thread};
15   std::thread t2{thread};
16   t1.join();
17   t2.join();
18   std::cout << a << '\n';
19 }

 

之前用的编译命令为:

/opt/compiler/gcc-4.8.2/bin/g++ test.cpp -I ./boost/include -std=c++11

需要改为:

/opt/compiler/gcc-4.8.2/bin/g++ test.cpp -I ./boost/include -std=c++11 -lpthread -Wl,--no-as-needed

这样运行就不会报错了。

 

本文参考自:https://stackoverflow.com/questions/19463602/compiling-multithread-code-with-g#

 

转载于:https://www.cnblogs.com/abc-begin/p/7919097.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Linux平台上,使用C++std::thread时可能会遇到崩溃的问题。这通常是由于没有启用多线程支持导致的。在引用中的情况中,错误信息显示“Enable multithreading to use std::thread: Operation not permitted”,提示需要启用多线程才能使用std::thread。为了解决这个问题,需要确保在编译和链接程序时启用多线程支持。在使用gcc编译器时,可以通过添加"-pthread"选项来启用多线程支持。例如,可以使用以下命令编译程序: ``` g++ -pthread -o program program.cpp ``` 这样就会在编译和链接过程中启用多线程支持,从而解决std::thread崩溃的问题。另外,还需要注意在使用std::thread时,确保在异常情况下调用join()或detach()来避免悬挂线程或资源泄漏。引用和中的代码示例展示了如何使用RAII机制和detach()函数来确保线程的正确管理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C++11 std::thread线程库](https://blog.csdn.net/code_peak/article/details/118200082)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [[C++]记在Linux下使用std::thread的错误](https://blog.csdn.net/sixdaycoder/article/details/81910816)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值