c++11 thread --多线程编译报错问题解决办法

在尝试使用C++11的多线程功能时,遇到'Operation not permitted'的编译错误。解决方法是在g++编译命令中添加-Wl,--no-as-needed选项,完整编译指令为:g++ -std=c++11 -Wl,--no-as-needed test.cpp -pthread -o test.out,这样可以成功编译并运行多线程程序。" 103267497,9130936,Python实现数字到人民币读法转换,"['Python编程', '编程实践', '数据转换']

//test.cpp
#include <stdio.h>
#include <iostream>

#include <thread>
#include <mutex>

std::mutex mMutex;

using namespace std;

static int count=0;
static int MAX=5000;
static int line=0;
static int line_count=5;

void thread1(){
    while(1){
        if(count <MAX ){
            mMutex.lock();
            if(count <MAX ){
                std::cout<<"A: "<<++count<<"    ";
                if(++line == line_count){
                    std::cout<<endl;
                    line = 0;
                }
            }else{
                break;
            }
            mMutex.unlock();
        }
    }
}

void thread2(){
    while(1){
        if(count <MAX ){
            mMutex.lock();
            if(count <MAX ){
                std::cout<<"B: "<<++count<<"    ";
                if(++line == line_count){
                    std::cout<<endl;
                    line = 0;
                }
            }else{
                break;
            }
            mMutex.unlock();
        }
    }
}

int main()
{
        std::thread mThread1(thread1);
        std::thread mThread2(thread2);
        mThread1.detach();
        mThread2.detach();

    while(1){
        int x;
        std::cin>>x;
        if(x==0){
            break;
        }
    }

    return 0;
}



在终端中执行:

 g++ -std=c++11   test.cpp  -pthread -o test.out


编译报错:

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

在网上查阅资料测试加上-Wl,--no-as-needed 就能正常编译运行了,完整的执行指令为:
 g++ -std=c++11  -Wl,--no-as-needed  test.cpp  -pthread -o test.out

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值