帮忙贴下您的运行结果
顺便说明下您使用的操作系统和编译器及其版本,谢谢了。
#include <chrono>
#include <future>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
std::mutex g_display_mutex;
void PrintThreadId() {
std::this_thread::sleep_for(std::chrono::seconds(2));
{
std::lock_guard<std::mutex> lock(g_display_mutex);
std::cout << std::this_thread::get_id() << std::endl;
}
}
int main(int argc, char* argv[]) {
std::vector<std::future<void>> futures;
for (int i = 0; i < 10; ++i) {
futures.emplace_back(std::async([]{
return PrintThreadId();
}));
}
for (std::future<void>& future : futures) {
future.wait();
}
}
vegertar@mac:/tmp$ uname -a
Darwin mac.vegertar 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 x86_64
vegertar@mac:/tmp$ c++ -v
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix
vegertar@mac:/tmp$ c++ -std=c++11 a.cc
vegertar@mac:/tmp$ ./a.out
0x10e4b2000
0x10e42f000
0x10e3ac000
0x10e535000
0x10e5b8000
0x10e63b000
0x10e6be000
0x10e741000
0x10e7c4000
0x10e847000
3077957328
3077957328
3077957328
3077957328
3077957328
3077957328
3077957328
3077957328
3077957328
3077957328
futures.emplace_back(std::async(std::launch::async, []{
return PrintThreadId();
}));
3078294384
3069901680
3059411824
3034233712
3042626416
3051019120
3017448304
3025841008
3009055600
3000662896
3078301392
(30.6.4) on an asynchronous return object referring to this shared state shall invoke the deferred function in the thread that called the waiting function.
所以,g++ 选择同一线程以及其它实现选择多线程都符合标准,实际上 30.6.8/9 特地说明了这个问题。
要想确保多线程执行,用户必须自己说清楚。
[解决办法]
mingw4.8.0 ( 不使用std::launch::async )
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1
9: 1
5: 7
3: 5
7: 9
1: 3
9: 11
2: 4
0: 2
4: 6
6: 8
8: 10