Wes Miller
Wes Miller

Reputation: 2241

In C/C++ on linux, how do I create a prelocked mutex

What attribute do I use to create a pthreads mutex that is locked by the creating thread at creation time?

Upvotes: 2

Views: 533

Answers (4)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215577

There is no observably-distinct difference between a mutex that is created in the locked state, and one that is created and subsequently locked by the thread that creates it. That is, if you write (hypothetical):

pthread_mutex_init(&mutex, &prelocked_attr);
/* done */

versus

pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&done);
/* done */

In both cases, it's UB for any other thread to attempt in any way to access the mutex before the creating thread reaches the "done" comment and subsequently performs some action that could let other threads know the mutex exists.

The fact that you think you need a pre-locked mutex suggests strongly to me that you're trying to do something very very wrong, and probably invoking undefined behavior.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254741

You can't. If you need to do that, you will have to lock it before allowing other threads access to it. You will have to do something like that anyway, to prevent other threads accessing it before initialisation is complete.

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78973

The closest you can get with what you want is to use semaphores. They can be initialized with a specific value. On linux (as you have that tag) man sem_overview should give you a good introduction to that topic

Upvotes: 2

tbert
tbert

Reputation: 2097

It doesn't appear to be supported by the pthreads mutex interfaces. You're going to have to mutually lock it, and use some other synchronization method to keep other threads from grabbing it before you do (which is what I'm assuming you want to do here), in semi-pseudocode below:

pthread_mutex_lock(my_pthread_creation_mutex);

pthread_mutex_init(new_mutex, mutex_attributes);
pthread_mutex_lock(new_mutex);

pthread_mutex_unlock(my_pthread_creation_mutex);

Upvotes: 2

Related Questions