简体   繁体   中英

where to unlock mutex in pthread?

Is it a good practice to lock a mutex from the main thread, and release from another thread?

Or should I make sure a thread will do it all in one? ie: lock, and unlock

http://www.manpagez.com/man/3/pthread_mutex_unlock/

(also from the POSIX spec site: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html )

If the current thread holds the lock on mutex, then the pthread_mutex_unlock() function unlocks mutex.

Calling pthread_mutex_unlock() with a mutex that the calling thread does not hold will result in undefined behavior.

A mutex can only be unlocked by the same thread that locked it. A program that violates this rule has undefined behavior and is not portable or stable; it may seem to work at times and fail horribly at other times, when compiled on a slightly different system, during a different phase of the moon, or after you upgrade.

If you really need this sort of behavior (locking by one thread and unlocking by another), a semaphore may meet your needs. Semaphores do not have owners, and any thread may call sem_post or sem_wait at basically any time.

It is bad practice to lock in one thread and unlock in another thread as this will require the two threads to communicate with each other. A thread should perform its own locking and unlocking.

It's never good practice to lock from one thread and unlock from another. The name says it all -- mutual exclusion. A thread that takes it holds it until done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM