Quick Q: Are std::threads run in the order they're created?--StackOverflow

Quick A: There is no guarantee that threads will run in a given order.

Recently on SO:

Why don't these threads run in order?

When I run this code:

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

I get the output:

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?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.