简体   繁体   English

在pthread中解锁互斥锁的位置?

[英]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/ 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 ) (也来自POSIX规范网站: 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. 如果当前线程持有锁定在互斥锁上,则pthread_mutex_unlock()函数将解锁互斥锁。

Calling pthread_mutex_unlock() with a mutex that the calling thread does not hold will result in undefined behavior. 使用调用线程未保留的互斥锁调用pthread_mutex_unlock()将导致未定义的行为。

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. 信号量没有所有者,任何线程都可以在任何时候调用sem_postsem_wait

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. 接受它的线程一直持有它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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