带有代码:的线程在运行时阻止错误

thread with code::blocks error at runtime

本文关键字:运行时 错误 线程 代码      更新时间:2023-10-16

编译此文件:

//Create a C++11 thread from the main program
#include <iostream>
#include <thread>
//This function will be called from a thread
void call_from_thread()
{
    std::cout << "Hello, from thread! " << std::endl;
}
int main()
{
    std::cout << "Hello, from main! " << std::endl;
    //Launch a thread
    std::thread t1(call_from_thread);
    //Join the thread with the main thread
    t1.join();
    return 0;
}

使用选中copmpiler选项"use C++11"的代码::块。

代码::块编译器说:g++-Wall-fexceptions-g-std=c++11-pthread-c/home/main.cpp-o obj/Debug/main.o

请注意,-std=c++11-pthread已传递给编译器。

运行程序时,收到以下消息:

Hello, from main! 
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)
Process returned 134 (0x86)   execution time : 0.110 s
Press ENTER to continue.

如何完成这项工作?谢谢你的帮助。

====================

PS。我看过这篇用g++编译多线程代码的文章。然后尝试使用技巧

我试过这个:

g++-Wall-fexceptions-g-std=c++11-pthread-Wl-无需-c/home/olivier/main.cpp-o obj/Debug/main.o

但得到了以下内容。

g++: error: unrecognized command line option ‘-Wl’
g++: error: unrecognized command line option ‘--no-as-needed’

如果使用-phread编译,则应使用-lpthread链接。

第二个很简单,它必须是:-Wl,--no-as-needed(缺少","),但它用于链接器。你的调用只编译成一个对象文件,所以你可以擦除它。

关于第二个注意事项,可能是由于某些gcc版本中的错误,您实际上必须与-Wl,--no-as-needed链接

对于代码::块,您可以在构建选项的链接器选项卡中添加-Wl,--no-as-needed和-lpthread。