wolf
wolf

Reputation: 127

Multiple threads attempting to lock

I want to use pthreads and pthread_mutexes in a C++ program. I don't have any actual code yet, just a question on how mutexes work. If I have thread 1 lock a mutex, then n number of other threads attempt to lock that same mutex, what will the behavior be when thread 1 unlocks the mutex? If thread 1 acquires the lock, then thread 2 attempts to lock, then thread 3 attempts to lock, will thread 2 have priority over thread 3 when the lock is released?

Here is a more organized timeline of the locking would look:

thread 1 acquires lock
thread 2 attempts to lock
thread 3 attempts to lock
thread 4 attempts to lock
thread 1 unlocks mutex
??

in other words, I'd like the threads to execute in the order in which they attempt to acquire the lock/are created. if there is a better way to do this, I'm more than open to suggestions.

Upvotes: 1

Views: 215

Answers (2)

wolf
wolf

Reputation: 127

I figured I'd post my solution so others could see a potential fix:

My main thread is the thread that creates worker threads by locking a creation mutex and putting each thread into a std::queue.

at the start of main, I create a manager thread and that is in an infinite while loop which checks to see if the queue is empty every cycle. when the manager thread sees the queue is nonempty (if(! queue::empty())), it waits to acquire the lock and then creates the front thread, pops it from the queue, executes a pthread_join() on the thread and loops back around for the next thread.

Upvotes: 0

Sid
Sid

Reputation: 7631

No - there will be no such guaranteed ordering. After thread 1 releases the mutex thread 3 could get or thread 2 could get it. You can't predict that.

Read this for an explanation.

Upvotes: 4

Related Questions