Giffyguy
Giffyguy

Reputation: 21292

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?

Upvotes: 8

Views: 6880

Answers (1)

selbie
selbie

Reputation: 104504

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.

Upvotes: 9

Related Questions