Linked Questions

Popular Questions

C++ Unexpected Multithreading Behaviour

Asked by At

I am working with multi-threading in C++ using a mutex. My code is below:

#include "stdafx.h"
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
using namespace std;

std::mutex mu;

void shared_print(string msg, int i) {
    std::lock_guard<std::mutex> guard(mu);
    cout << msg << i << endl;
}

void function_1() {
    for (int i = 0; i > -3; i--)
        shared_print("Thread1: ", i);
}

int main() {
    std::thread thread1(function_1);

    for (int i = 0; i < 3; i++)
        shared_print("Main: ", i);

    thread1.join();
    return 0;
}

From my understanding, the mutex will only allow access to a single resource at a time. So the mutex will be locked by the first thread that calls it (Thread1). When the main thread attempts to access the mutex, it is blocked until the mutex has been unlocked by Thread1. It will be unblocked once cout has executed upon which main will be allowed to execute.

I expect the result to be interleaving calls such as Thread1, Main, Thread1, Main etc.

However, instead I get the below result on standard out. The pattern remains the same for any number of iterations:

Thread1: 0
Thread1: -1
Thread1: -2
Main: 0
Main: 1
Main: 2

Related Questions