简体   繁体   English

线程如何获取互斥锁?

[英]How does a thread acquire a mutex lock?

My question here is about a thread acquiring a mutex lock. 我的问题是关于获取互斥锁的线程。

We use pthread_mutex_t locks to ensure sequential access to variables, when being read/written in a multi-threaded program. 当在多线程程序中读写时,我们使用pthread_mutex_t锁来确保顺序访问变量。 But pthread_mutex_t lock ; 但是pthread_mutex_t lock ; is also a global variable shared between threads. 也是线程之间共享的全局变量。 Will accessing of this global variable (the lock) be the same as accessing other global variables? 访问全局变量(锁)是否与访问其他全局变量相同? If it is the same, then won't we face the same problem that we will face for other global variables? 如果相同,那么我们是否将面对与其他全局变量一样的问题? And if not, then how accessing a lock data structure different from accessing other global variables? 如果不是,那么如何访问不同于访问其他全局变量的锁数据结构?

In short: Why don't we need to lock access to locks themselves and so end up in a chicken-and-egg problem? 简而言之:为什么我们不需要锁定自己对锁的访问权限,而最终遇到鸡与蛋的问题呢?

You don't really access pthread_mutex_t variables directly, you access them with some given functions ( pthread_mutex_lock for example). 您实际上并没有直接访问pthread_mutex_t变量,而是使用某些给定的函数(例如pthread_mutex_lock )访问它们。

These functions are built so that there is no concurrent access to these structures, either by the use of some test-and-set instruction ( http://en.wikipedia.org/wiki/Test-and-set ) or by using some atomic portion of code ( http://en.wikipedia.org/wiki/Linearizability ). 建立这些功能的目的是通过使用某些测试设置指令( http://en.wikipedia.org/wiki/Test-and-set )或使用某些测试设置指令,而不会同时访问这些结构。代码的基本部分( http://en.wikipedia.org/wiki/Linearizability )。

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

相关问题 linux中的pthread_mutex_t是否是可重入的(如果一个线程试图获取它已经持有的锁,则请求成功) - Does pthread_mutex_t in linux are reentrancy (if a thread tries to acquire a lock that it already holds, the request succeeds) 如何在本地使用互斥变量锁定线程? - How to lock thread by using mutex variable locally? pthread_mutex_lock当它是同一个线程时如何不锁定 - pthread_mutex_lock how to not lock when it is the same thread 子级无法获取共享内存区域中的互斥锁 - Child Fails to Acquire Mutex Lock in Shared Memory Region pthread_mutex_lock和pthread_mutex_lock在另一个线程中 - pthread_mutex_lock and pthread_mutex_lock in another thread 尝试获取pthread_mutex_lock(&mutex)的线程如果他们没有获得锁定会发生什么? - Threads trying to acquire pthread_mutex_lock(&mutex) What happens if they don't get the lock? 互斥锁和解锁功能如何防止 CPU 重新排序? - How does a mutex lock and unlock functions prevents CPU reordering? 在同一个线程中多次锁定互斥锁 - Lock a mutex multiple times in the same thread 在 pthread_mutex_lock 期间杀死线程 - Kill thread during pthread_mutex_lock 线程互斥:mutex_lock 用 mutex_trylock 实现 - Thread mutual exclusion: mutex_lock implemented with mutex_trylock
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM