为什么这些线程不顺序运行? [英] Why don't these threads run in order?

查看:185
本文介绍了为什么这些线程不顺序运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行此代码时:

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

我得到输出

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

虽然我使用互斥量一次只保留一个线程访问。为什么不按顺序输出?

Even though I used a mutex to keep only one thread access at a time. Why isn't the output in order?

推荐答案

您的互斥体实现的是没有两个线程同时打印。然而,他们仍然是赛跑,线程首先获得互斥量。

What your mutex achieves is that no two threads print at the same time. However, they are still racing for which thread acquires the mutex first.

如果你想有串行执行,你可以只是避免线程。

If you want to have serial execution you can just avoid threads at all.

这篇关于为什么这些线程不顺序运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆