tem*_*boy 7 c++ multithreading c++11
当我运行此代码时:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
int main()
{
std::vector<std::thread> workers;
for (int i = 0; i < 10; ++i)
{
workers.emplace_back([i]
{
std::lock_guard<std::mutex> lock(m);
std::cout << "Hi from thread " << i << std::endl;
});
}
std::for_each(workers.begin(), workers.end(), [] (std::thread& t)
{ t.join(); });
}
Run Code Online (Sandbox Code Playgroud)
我得到输出:
Hi from thread 7
Hi from thread 1
Hi from thread 4
Hi from thread 6
Hi from thread 0
Hi from thread 5
Hi from thread 2
Hi from thread 3
Hi from thread 9
Hi from thread 8
Run Code Online (Sandbox Code Playgroud)
即使我使用互斥锁一次只能访问一个线程.为什么输出没有顺序?