c++ - 使用 Code::Blocks GNU 编译器编译多线程代码

标签 c++ linux multithreading c++11 compilation

错误

我正在尝试使用 std::thread 但是当我尝试运行它时出现此错误。

terminate called after throwing an instance of 'std::system_error'

what(): Enable multithreading to use std::thread: Operation not permitted

Aborted (core dumped)

我的研究结果

关于它有很多的问题,每个答案都说类似的话: 我必须使用“-pthread”或“-lpthread”进行构建。也有人说要加上“-Wl,--no-as-needed”。

Link Link Link Link Link Link Link

我尝试了很多东西,但都没有用。

详情

我在 Lubuntu 上使用 Code::Blocks 12.11,GNU GCC 编译器进行编译。 在编译器设置菜单中,我检查了编译器标志

"Have g++ follow the C++11 ISO C++ language standard [-std=c++11]"

在其他选项下我写下了答案,这里是一个例子

-pthread
-Wl,--no-as-needed

这是我的构建日志(我不确定它是否重要)

g++ -Wall -fexceptions  -std=c++11 -g -pthread -Wl,--no-as-needed  -std=c++11   -I../DeskManagerDll -I/usr/include/X11/extensions -I/usr/include/X11  -c /home/julien/Documents/test/main.cpp -o obj/Debug/main.o
g++ -L/home/julien/Documents/DeskManagerDll -L-L/usr/lib/i386-linux-gnu  -o bin/Debug/test obj/Debug/main.o   -L/usr/X11R6/lib  -lX11 -lXext -lpthread -Wl,--no-as-needed  /home/julien/Documents/DeskManagerDll/bin/Debug/libDeskManagerDll.so 
Output size is 187,15 KB

我的问题

我做错了什么?我错过了什么?

编辑

我做了一个非常简单的程序来排除任何其他问题。

#include <thread>

void test()
{
    
}

int main()
{
    std::thread thread_fct (test);
    return 0;
}

此程序的构建日志:

g++ -Wall -fexceptions  -std=c++11 -g -pthread -Wl,--no-as-needed  -std=c++11    -c /home/julien/Documents/test/main.cpp -o obj/Debug/main.o
g++  -o bin/Debug/test obj/Debug/main.o    

我仍然遇到完全相同的错误。我真的不知道该尝试什么。 你有什么想法吗?

最佳答案

您的第一个问题是 -lpthread 是一个链接器选项,因此它属于链接器行(第二个命令)而不是编译行。 (请注意,参数的顺序可能很重要;我通过将 -lpthread 放在 last 上来让它工作。我也尝试使用 -pthread而不是 -lpthread,后者似乎确实有效,而且对它在链接器行上的位置不太敏感。但同样,它是一个链接器选项,而不是 < em>编译选项。)

修复该问题后,我能够让您的程序编译和运行,但它退出时出现不同的异常:terminate called without an active exception。要解决此问题,请在 main() 中调用 thread_fct.join();。 (所有线程在超出范围之前必须加入、分离或移动,否则您的程序将中止。)

关于c++ - 使用 Code::Blocks GNU 编译器编译多线程代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23677690/

相关文章:

java - 如何确定和使用 Linux shell 脚本中的实际 java 路径

c++ - 条件变量和无锁容器

c++ - QThread 移动到线程。 QThread 中的同步

c++ - 如何将字符数组的一部分附加到字符串?

c++ - 我的 C++ 窗口出现错误

linux - 在 bash 文件末尾添加一行

linux - 使用 :"pip install ."从源代码构建不适用于 sudo

c++ - CBT Hook 仅接收一些事件

java - 如何使用 invokeAll() 让所有线程池完成任务?

java - 通过 executorservice 进行顺序事件处理