MinGW和std :: thread

11

我一直在尝试使用MinGW编译器在Windows上编译和运行以下代码。

#include <iostream>
#include <thread>

void test()
{
    std::cout << "test" << std::endl;
}

int main()
{
    std::thread t(test);
}

我正在使用以下命令进行编译:

g++ -std=c++11 test.cpp -o test.exe

现在的问题是应该使用哪个版本的MinGW,我已经尝试了我知道的所有版本。

  1. MinGW-builds: thread-win32(线程库Win32版)
  2. MinGW-builds: thread-posix(线程库POSIX版)
  3. MinGW-w64: stdthread experimental rubenvb(C++11标准线程实验性支持,rubenvb版)
  4. MinGW-w64: stdthread experimental rubenvb 4.7(C++11标准线程实验性支持,rubenvb 4.7版)

第一种方法不可行,因为GCC 显然仅在内部支持 pthread 相关内容。

第二种方法可以编译,并且基本上输出了test(请参见输出的最后一行),但它也会崩溃并显示以下错误:

terminate called without an active exception

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
test

第三和第四个编译通过了,但是它们并没有输出test,而是立即崩溃,但输出的信息更加详细:

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

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Google将我带到了GCC错误跟踪器和一些其他帖子,建议使用-pthread,但这根本没有帮助。
我还尝试手动链接winpthreadpthread,但也没有任何作用。 -std=c++11-std=gnu++11之间也没有区别...
我现在真的很迷茫,不知道是否有可能获得支持std::thread的MinGW版本,但也许我只是忽略了一些编译器标志。我希望那里的某个人能帮助我!

花了几个小时才找到解决方案,最终第二点有效!谢谢! - Massimo
2个回答

10

您忘记加入线程:

t.join();

2
好的,我想我现在要自杀了...但为什么它要返回这样一个神秘的错误?它仍然不能与所有版本一起使用,但至少可以使用其中一个。谢谢! - Lukas
3
销毁可联结线程会导致抛出异常。由于您没有捕获异常,程序将终止。 - Kerrek SB

4

提醒一下,已经有一个本地的win32实现std::thread和同步原语了。它是一个只有头文件的库,并且可以在任何符合C++11标准的MinGW版本上使用。 https://github.com/meganz/mingw-std-threads


1
这并不是对已经解决的问题的真正回答,因此留言可能更合适。不过还是感谢您的分享! - Lukas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接