What data type is a mutex?
I want to set an int as a mutex.
I see that the locks are set to ints and a mutex is declared as so pthread_mutex_t mtx where does one set the data type for the mutex or connect the mutex to the variable?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think you’re mistaken about how mutexes work. They don’t have a type (other than
pthread_mutex_tobviously).You can use them to protect a shared resources by making the threads that manipulate the resource all lock the same mutex when they need to operate on that resource.
What happens then is that, since only one thread at a time can hold the mutex locked, the other threads trying to access the shared resource will be blocked.
Once the thread that got the lock has finished using that resource, it must unlock the mutex – otherwise the other threads will block forever.
The exact nature of the resource you “protect” with this mutex is up to you. It could be a simple
int, a complex structure, some hardware resource… You’re responsible for making sure that all accesses to that resource from your code always locks and unlocks the mutex you created to protect it.A reference you might find usefull: POSIX Threads Programming