在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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
http://www.manpagez.com/man/3/pthread_mutex_unlock/
(也来自 POSIX 规范站点: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html)
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)
互斥体只能由锁定它的同一线程解锁。违反此规则的程序具有未定义的行为并且不可移植或稳定;当在稍微不同的系统上编译时、在不同的月相期间或在升级之后,它似乎有时可以工作,而有时却会严重失败。
如果您确实需要这种行为(由一个线程锁定并由另一个线程解锁),信号量可能会满足您的需求。信号量没有所有者,任何线程基本上可以随时调用 sem_post 或 sem_wait 。
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
orsem_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.