Namespaces
Variants
Views
Actions

Talk:cpp/thread/lock

From cppreference.com

This sample code does not display the cout messages properly. I am using Microsoft Visual Studio 2013. The reason is the code snippet below. The lock lk expires as soon as the block ends at "}". The subsequent code does not have a lock on io_mutex. Hence, the cout messages are interlaced.

void assign_lunch_partner(Employee &e1, Employee &e2)
{
    {  
        static std::mutex io_mutex;
        std::lock_guard<std::mutex> lk(io_mutex);
        std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl;
    }
...

Change to the code below fixed the cout message issue.

void assign_lunch_partner(Employee &e1, Employee &e2)
{
    static std::mutex io_mutex;
    if (!io_mutex.try_lock()) { // if io_mutex is locked by another thread
        while (!io_mutex.try_lock()) {  //  this thread must wait as long as io_mutex is locked.
           // wait for the other thread completes its cout before calling try_lock() again
           std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        // No interlaced message now because this thread locked io_mutex using try_lock() above.
        std::cout << e1.id << " and " << e2.id << " were waiting for locks" << std::endl;
    }
    io_mutex.unlock();
    std::lock_guard<std::mutex> lk(io_mutex);
...

Longbow (talk) 11:46, 5 May 2016 (PDT)

true, reproduces with other compilers too, although sleeping and mutex.unlock are both antipatterns. Let's just use io_mutex around both io operations. --Cubbi (talk) 12:01, 5 May 2016 (PDT)

Thanks for the comment, Cubbi. I don't know how to print out the message that io_mutex is being locked by another thread ("... were waiting for locks") without using the try_lock() call. I have to unlock() it in case the try_lock() call locked it.

Otherwise, the above code would look like below, as I understand it. Can you please advise?

void assign_lunch_partner(Employee &e1, Employee &e2)
{
    static std::mutex io_mutex;
    std::lock_guard<std::mutex> lk(io_mutex); // this line blocks until the io_mutex is available.
...
--Longbow (talk) 05:45, 6 May 2016 (PDT)

[edit] Comment wording in the example

From the example:

 // Equivalent code (if unique_lock's is needed, e.g. for condition variables)

unique_lock's what is needed? Is there a word missing? Kumiponi (talk) 12:33, 6 October 2016 (PDT)

made it say "unique_locks are", thanks --Cubbi (talk) 12:57, 6 October 2016 (PDT)