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

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

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

测试代码:

#include 
#include 
#include 
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 
#include 
#include 
#include 

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下运行,则正常。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/662425.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-18
下一篇 2022-04-18

发表评论

登录后才能评论

评论列表(0条)

保存