Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a single thread double-lock a mutex?

If I want a thread to pause for a while, until certain conditions are met, can I double-lock the mutex?

Here's a basic example of the idea I'm working with right now:

class foo
{
public:
    static std::mutex processingMutex;

    void infinite_processing_loop()
    {
        processingMutex.lock();  // Lock the mutex, initially

        while(true)
        {
            if ( /*ready for this thread to process data*/ )
            {
                // ... perform one round of data processing ...
            }
            else  // NOT ready for this thread to process data
            {
                /* Pause this thread,
                   and wait for another thread to unlock this mutex
                   (when more data might be ready for processing) */

                processingMutex.lock();
            }
        }

        processingMutex.unlock();  // Will never be executed
    }
};

Will the processing thread halt, when it tries to double-lock the mutex?
And can another thread unlock the same mutex, causing the halted processing thread to resume?

Or does std::mutex automatically recognize when mutex is locked twice from the same processing thread?

like image 801
Giffyguy Avatar asked Feb 09 '18 23:02

Giffyguy


People also ask

Can a thread lock a mutex twice?

To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.

Can multiple threads lock the same mutex?

The reverse is also true (the first thread will block for as long as the second thread has the mutex). In other words, as long as one thread has a lock on a mutex, no other thread can lock the same mutex.

Can a thread acquire multiple locks mutex?

While mutex is owned by the thread, no other thread can acquire mutex , so no other thread can be executing between either of the lock(mutex); / unlock(mutex); pairs (one at the top of the Reader function and one further down).

Can the same thread acquire a lock twice?

Typically, threads cannot acquire locks twice in a row: a thread must release an acquired lock before attempting to acquire it again. However, reentrant locks can be acquired multiple times by the same thread. Reentrant locks allow code to acquire a lock before calling other functions that acquire the same lock.


1 Answers

std::mutex will usually deadlock on second attempt to lock by the owner thread. And even if it didn't, it's considered a bug for an application to attempt with this primitive.

std::recursive_mutex will allow re-entrant locks. So if you lock twice, you need to unlock twice before the mutex is available for other threads to grab.

There's a school of thought that any design that involves recursively acquiring a mutex after it's already been locked is a design flaw. I'll try to dig up that thread and add it.

like image 137
selbie Avatar answered Oct 06 '22 00:10

selbie