c++11 thread类在嵌入式上运行报错问题

从昨晚到今天遇到一个怪异的问题,暂时无解,先记录在此。

测试代码:

#include <iostream>
#include <unistd.h>
#include <thread>
using namespace std;
void  func1()
{
    cout<<"AAAAAAAAAA"<<endl;
}

int main()
{
    thread(func1).detach();
    sleep(2);
    cout<<"BBBBBBBBBB"<<endl;
    return 0;
}

代码非常简单,使用c++11新增的thread类,创建一个子线程。

qt工程的.pro文件中,已添加thread库和c++11支持:

.pro文件

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
        main.cpp
LIBS += -pthread

编译后在imx6开发板上运行报错:

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

在这里插入图片描述百度了一遍,都是说要在.pro文件中添加-pthread(或-lpthread),但是我.pro文件中已经添加了,仍然报错。反复测试无果。

后来,想着用linux的pthread试试。修改下代码:

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

using namespace std;

void  func1()
{
    cout<<"AAAAAAAAAA"<<endl;
}

void *func2(void* arg)
{
    cout<<"CCCCCCCCC"<<endl;
}


int main()
{
    thread(func1).detach();
    sleep(1);
    pthread_t pid;
    pthread_create(&pid, NULL, func2, NULL);
    sleep(1);
    cout<<"BBBBBBBBBB"<<endl;
    return 0;
}

惊喜了……正常运行!!!
在这里插入图片描述
所以,现在的问题是:thread类在嵌入式平台下,交叉编译后无法单独使用。经测试,代码中至少要调用pthread中的一个函数才能正常运行。
如调用了pthread_attr_init()或者pthread_creat()。

但是,如果是用桌面编译器,编译后在ubuntu下运行,则正常。

期待高手解惑,不胜感激!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值