簡體   English   中英

如何在MinGW中啟用實驗性C ++ 11並發功能?

[英]How to enable experimental C++11 concurrency features in MinGW?

在嘗試編譯以下代碼時

#include <thread>
#include <iostream>

void foo() { std::cout << "foo\n"; }

int main()
{
  std::thread t(foo);
  t.join();
}

我收到一個錯誤:

C:\Test>g++ -g -Wall -lpthread -std=c++0x
main.cpp
main.cpp: In function 'int main()':
main.cpp:12:2: error: 'thread' is not a member of 'std'
main.cpp:12:14: error: expected ';' before 't'
main.cpp:13:2: error: 't' has not been declared

如何使用C ++ 11實驗並發功能? 我有MinGW GCC 4.5.1(TDM)

編輯: BTW,Visual Studio 2012執行良好的代碼示例。

據我所知,MinGW還不支持新的c ++ 0x並發功能(從GCC 4.5開始)。 我記得讀過一個郵件列表交換,其中指出在MinGW中,以下來自線程頭的ifdef不滿足:

#if defined(_GLIBCXX_HAS_GTHREADS)

我想這與MinGW在Windows下構建的方式有關,無論是使用本機線程還是pthread等。在我的代碼中,我編寫了一些使用Boost.thread而不是本機c ++ 0x線程的最小包裝。在Windows中。 這兩個接口非常相似,對於許多用途,它們可以毫無問題地進行交換。

編輯 :感謝Luc Danton挖掘出上面提到的郵件列表主題:

http://comments.gmane.org/gmane.comp.gnu.mingw.user/33065

我目前正在努力獲得一個使用新的mingw-w64 winpthreads庫的GCC。 這將在GCC中啟用posix線程模型,並且正在開展工作以使其按預期工作。 另一個mingw-w64用戶已經通過黑客攻擊(明智地)實現了這一功能,但是我試圖在主線GCC中完成它,在工具鏈安裝后沒有人工干預。

這里可以遵循目前的討論。 一旦所有粗糙邊緣被平滑,我將更新此答案。

編輯 :由於一個upvote,這個答案引起了我的注意。 我已經構建了一個實驗性的GCC 4.7,它應該與std::thread ,但是只有在靜態鏈接時(將add -static添加到link命令)。 宣布就在這里

C ++ 0x庫狀態頁面表明它已經實現,但您可能需要一個SVN版本來獲取該頁面上列出的所有內容。 這個頁面看起來會幫助你獲得前沿構建。

正如其他人所提到的,gcc的mingw端口不提供開箱即用的C ++ 0x並發支持。 但是,商業just :: thread庫提供了這些功能,因此您可以將std::threadgcc 4.5.2TDM / mingw端口一起使用。

免責聲明:我是just :: thread庫的主要開發人員。

已經存在std :: threads和sync基元的輕量級本機實現: https//github.com/meganz/mingw-std-threads

它是一個僅限標頭的庫,它應該適用於任何C ++ 11版本的MinGW。

當你得到一個支持std::thread的編譯器時,這是你更正的例子(兩個次要類型-o):

#include <thread>
#include <iostream>

void foo() { std::cout << "foo\n"; }

int main()
{
  std::thread t(foo);
  t.join();
}

嘗試MinGw構建:

http://sourceforge.net/projects/mingwbuilds/

此安裝程序將允許您選擇所需的MinGW,還包括c ++ 11線程功能。

還有另一種選擇。

//Threading01.cpp

#include <thread>
#include <iostream>

void hello()
{
    std::cout<< "Hello Threading ..." << std::endl;
}

int main()
{
    std::thread t1(hello);
    t1.join();

    return 0;
}

下載mingw-w64 (sourceforge.net上的mingw-w64項目正在轉移到mingw-w64.org )並執行他們提供的.bat文件(mingw-w64.bat)。在提供的命令行中,您可以執行您的線程像這樣的代碼

C:\CPP>g++ std=c++11 -g -Wall -lpthread -o Threading01 Threading01.cpp

暫無
暫無

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

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