在pthread中哪里解锁互斥体?

发布于 2024-12-01 22:38:09 字数 73 浏览 1 评论 0原文

从主线程锁定互斥体并从另一个线程释放互斥体是一个好习惯吗?

或者我应该确保一个线程能够同时完成这一切?即:锁定和解锁

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白日梦 2024-12-08 22:38:09

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

(也来自 POSIX 规范站点: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html

如果当前线程持有互斥锁,则
pthread_mutex_unlock()函数解锁互斥锁。

使用调用线程的互斥体调用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)

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.

酒与心事 2024-12-08 22:38:09

互斥体只能由锁定它的同一线程解锁。违反此规则的程序具有未定义的行为并且不可移植或稳定;当在稍微不同的系统上编译时、在不同的月相期间或在升级之后,它似乎有时可以工作,而有时却会严重失败。

如果您确实需要这种行为(由一个线程锁定并由另一个线程解锁),信号量可能会满足您的需求。信号量没有所有者,任何线程基本上可以随时调用 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 or sem_wait at basically any time.

善良天后 2024-12-08 22:38:09

锁定一个线程并解锁另一个线程是一种不好的做法,因为这将需要两个线程相互通信。线程应该执行自己的锁定和解锁。

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.

丶情人眼里出诗心の 2024-12-08 22:38:09

从一个线程锁定并从另一个线程解锁从来都不是一种好的做法。这个名字说明了一切——相互排斥。接受它的线程将保留它直到完成。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文