jakaspeh / concurrency

32 stars 9 forks source link

serialize the lock scopes #1

Open azadkuh opened 6 years ago

azadkuh commented 6 years ago

just read your nice blog Mutex and deadlock with this example:

https://github.com/jakaspeh/concurrency/blob/490fcded951eb7ffb46ff182fea8131cf525be8f/deadlock.cpp#L11

although the whole article is about the deadlock and introducing the std::lock<>() the best way to do that is by serializing the mutex scopes.

as long the muteces in this example do not relate to each other, it would be nice and even easier to tighten the lock scopes and release them ASAP:

void makeAppleJuice(std::vector<std::string>& bag)
{
    // unlock as soon as possible
    {
        std::lock_guard<std::mutex> printGuard(m_print);
        std:: cout << " ...";
    }

    // bag scope
    {
        std::lock_guard<std::mutex> bagGuard(m_bag);
        int numApples = 0;
        for (std::size_t i = 0; i != bag.size(); i++) {
            // ...
        }
    }

    // print scope
    {
        std::lock_guard<std::mutex> printGuard(m_print);
        if (numApples < 5) {
            // ...
        } else {
            // ...
        }
    }
}

serialization makes the code even more performant (more independent paths, better for parallelism).

the bank account example in cppreference.com requires the std::lock<>() because the locks are related in that example.

however, it was a nice and easy introduction to deadlock. kudos.

jakaspeh commented 6 years ago

Thank you for reading the blog! :-)

And thank you for the idea of tightening the lock scope! This indeed avoids the deadlock and makes the code more efficient.

I will leave the blog post as is -- my main motivation for it was to explain the deadlock.