cpp11dev
cpp11dev

Reputation: 417

std::thread C++ 11 fails to explain me why

I am running this very simple program, on Ubuntu 13.04 Desktop, however if I comment out the line sleep_for, it hangs after printing cout from main. Can anyone explain why ? As far as I understand, main is a thread and t is another thread and in this case the mutex manages synchronization for shared cout object.

#include <thread>
#include <iostream>
#include <mutex>

using namespace std;
std::mutex mu;

void show()
{
 std::lock_guard<mutex> locker(mu);
 cout<<"this is from inside the thread"<<endl;
}

int main()
{
 std::thread t(show);
 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
 std::lock_guard<mutex> locker(mu);
 cout<<"This is from inside the main"<<endl;
 t.join();
 return 0;
}

Upvotes: 3

Views: 251

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

That's just a classic deadlock: The main thread obtains the lock and then blocks on joining the other thread, but the other thread can only join if it manages to obtain the lock.

Upvotes: 2

nosid
nosid

Reputation: 50044

If you change to main function as follows, the code will work as expected:

int main()
{
    std::thread t(show);
    {
        std::lock_guard<mutex> locker(mu);
        cout << "This is from inside the main" << endl;
    } // automatically release lock
    t.join();
}

In your code, there is a unfortunate race condition. If the thread t gets the lock first, everything works fine. But if the main threads gets the lock first, it holds the lock until the end of the main function. That means, the thread t has no chance to get the lock, can't finish and the main thread will block on t.join().

Upvotes: 7

Related Questions