为什么这些线程不按顺序运行?

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)

即使我使用互斥锁一次只能访问一个线程.为什么输出没有顺序?

inf*_*inf 19

你的互斥体实现的是没有两个线程同时打印.但是,他们仍在竞争哪个线程首先获得互斥锁.

如果你想要串行执行,你可以完全避免线程.


Sil*_*cer 6

它完全取决于安排订单线程的操作系统.你不能依赖任何订单.假设它完全是随机的.