Why don't these threads run in order?
c++, c++11, multithreading
Solution
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.
Problem
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?