簡體   English   中英

如何在 Windows 上使用帶有 POSIX 線程的 MinGW 上的 std::thread

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

我一直在嘗試編譯並運行以下非常簡單的代碼

#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;
}

我正在使用 MinGW 6.3.0(目標 x86_64-w64-mingw32)在 Windows 10 上編譯,線程 model(使用g++ -v獲得)是 POSIX。

我沒有收到g++ -Wall -g test.cpp -o test.exe的任何編譯錯誤,但是在嘗試運行 exe 時出現運行時錯誤( entry point of _ZNSt6thread15_M_start_threadESt10unique_ptrINS_3_StateESt14default_deleteIS1_EEPFvve cannot be found )。

我還嘗試使用-pthread-lpthread標志進行編譯,但我遇到了相同的運行時錯誤。 顯然這似乎與 std::thread 的使用有關,但我不知道如何解決這個問題。 我是否缺少在 Windows 上啟用 POSIX 線程支持的編譯標志或附加庫?

編輯:我設法通過將編譯命令更改為g++ -Wall -g test.cpp -o test.exe -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,Bdynamic

在進行必要的修復后,我嘗試了您的代碼:

#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;
}

它工作正常。 構建命令與您的相同:

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

output 是:

012345678910Press any key to continue . . .

但我確實使用了 MinGW-w64 GCC 12.1.0(來自 https://winlibs.com/ )而不是非常舊的版本 6.3.0。

也許您使用的 MinGW-w64(或者它仍然是舊的 MinGW)庫太舊了......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM