简体   繁体   English

如何在 Windows 上使用带有 POSIX 线程的 MinGW 上的 std::thread

[英]How to use std::thread on Windows with MinGW with POSIX threads

I have been trying to compile and run the following very simple bit of code我一直在尝试编译并运行以下非常简单的代码

#include <thread>

using namespace std;

void thread_c() {
    for (int i = 0; i < 11; ++i) {
        cout << i;
    }
}

int main()
{
    thread t(thread_c);
    t.join();

    system("pause");
    return 0;
}

I am compiling on Windows 10 with MinGW 6.3.0 (target x86_64-w64-mingw32) and the thread model (obtained using g++ -v ) is POSIX.我正在使用 MinGW 6.3.0(目标 x86_64-w64-mingw32)在 Windows 10 上编译,线程 model(使用g++ -v获得)是 POSIX。

I am not getting any compilation error with g++ -Wall -g test.cpp -o test.exe , however I am getting a runtime error when trying to run the exe ( entry point of _ZNSt6thread15_M_start_threadESt10unique_ptrINS_3_StateESt14default_deleteIS1_EEPFvve cannot be found ).我没有收到g++ -Wall -g test.cpp -o test.exe的任何编译错误,但是在尝试运行 exe 时出现运行时错误( entry point of _ZNSt6thread15_M_start_threadESt10unique_ptrINS_3_StateESt14default_deleteIS1_EEPFvve cannot be found )。

I also tried compiling with the -pthread or -lpthread flags, but I am getting the same runtime error.我还尝试使用-pthread-lpthread标志进行编译,但我遇到了相同的运行时错误。 Obviously this seems to be related to the use of std::thread, but I didn't get how to fix this.显然这似乎与 std::thread 的使用有关,但我不知道如何解决这个问题。 Am I missing a compilation flag or additional library enabling POSIX thread support on Windows?我是否缺少在 Windows 上启用 POSIX 线程支持的编译标志或附加库?

Edit: I managed to get it working by changing the compilation command to g++ -Wall -g test.cpp -o test.exe -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,Bdynamic编辑:我设法通过将编译命令更改为g++ -Wall -g test.cpp -o test.exe -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,Bdynamic

I tried your code after making the necessary fixes:在进行必要的修复后,我尝试了您的代码:

#include <thread>
#include <iostream>

using namespace std;

void thread_c() {
    for (int i = 0; i < 11; ++i) {
        std::cout << i;
    }
}

int main()
{
    thread t(thread_c);
    t.join();

    system("pause");
    return 0;
}

and it worked fine.它工作正常。 The build command was the same as yours:构建命令与您的相同:

g++ -Wall -g test.cpp -o test.exe

The output was: output 是:

012345678910Press any key to continue . . .

But I did use MinGW-w64 GCC 12.1.0 (fro https://winlibs.com/ ) instead of the very old version 6.3.0.但我确实使用了 MinGW-w64 GCC 12.1.0(来自 https://winlibs.com/ )而不是非常旧的版本 6.3.0。

Maybe the MinGW-w64 (or was it still the old MinGW) library you were using was simply too old...也许您使用的 MinGW-w64(或者它仍然是旧的 MinGW)库太旧了......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM