pthread_mutex_lock()和pthread_mutex_unlock()做什么?
pthread_mutex_lock()
和pthread_mutex_unlock()
函数真的做什么。我知道锁定是使代码被阻止的,直到再次解锁为止。我仍然对在锁定和解锁的那个时期之间发生的事情感到困惑。
What do the pthread_mutex_lock()
and pthread_mutex_unlock()
functions really do. I understand that the lock makes it so that the code is blocked until it is unlocked again. I'm still confused on what happens in between that period where it is locked and unlocked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在C中,这是锁定和解锁静音的基本方法,
基本上是pthread_mutex_unlock()将停止锁定并等到程序要求发生另一个锁。
In C, this is the basic way to lock and unlock mutexes is
Basically pthread_mutex_unlock() will stop the lock and wait until the program asks for another lock to happen.
在最基本的情况下,每个硬件都有某种指令或一系列指令进行“测试和设置”:“作为一种原子操作,测试此变量是否具有值x,如果是的,则将其设置为y。我知道我是否成功。”
因此,我们有:
现在,该代码有两个基本问题:
实际实施情况会做更多。
mutex
包含有关当前拥有的互联克人(如果被锁定)的更多信息,以便只有该线程才能解锁。因此,实际代码更像:
At the most basic, every hardware out there has some sort of instruction or sequence of instructions that does "test and set": "As an atomic action, test if this variable has value x, and if so, set it to y. Let me know if I am successful".
So at it's heart, we have:
Now this code has two basic problems:
Actual implementations do a bit more. The
mutex
contains more information about who currently owns the mutex, if it is locked, so that only that thread can unlock it.So the actual code is more like: