- Mastering C++ Multithreading
- Maya Posch
- 193字
- 2021-07-15 17:34:03
Mutexes
These are functions prefixed with either pthread_mutex_ or pthread_mutexattr_. They apply to mutexes and their attribute objects.
Mutexes in Pthreads can be initialized, destroyed, locked, and unlocked. They can also have their behavior customized using a pthread_mutexattr_t structure, which has its corresponding pthread_mutexattr_* functions for initializing and destroying an attribute on it.
A basic use of a Pthread mutex using static initialization looks as follows:
static pthread_mutex_t func_mutex = PTHREAD_MUTEX_INITIALIZER;
void func() {
pthread_mutex_lock(&func_mutex);
// Do something that's not thread-safe.
pthread_mutex_unlock(&func_mutex);
}
In this last bit of code, we use the PTHREAD_MUTEX_INITIALIZER macro, which initializes the mutex for us without having to type out the code for it every time. In comparison to other APIs, one has to manually initialize and destroy mutexes, though the use of macros helps somewhat.
After this, we lock and unlock the mutex. There's also the pthread_mutex_trylock() function, which is like the regular lock version, but which will return immediately if the referenced mutex is already locked instead of waiting for it to be unlocked.
In this example, the mutex is not explicitly destroyed. This is, however, a part of normal memory management in a Pthreads-based application.
- Unreal Engine Physics Essentials
- 流量的秘密:Google Analytics網(wǎng)站分析與優(yōu)化技巧(第2版)
- Python快樂編程:人工智能深度學習基礎
- Raspberry Pi Networking Cookbook(Second Edition)
- C/C++算法從菜鳥到達人
- SSM輕量級框架應用實戰(zhàn)
- Functional Kotlin
- PySide GUI Application Development(Second Edition)
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- Java EE 8 Application Development
- 深度學習:Java語言實現(xiàn)
- Raspberry Pi Robotic Projects(Third Edition)
- Python預測分析實戰(zhàn)
- 創(chuàng)新工場講AI課:從知識到實踐
- Learning RSLogix 5000 Programming