- Mastering C++ Multithreading
- Maya Posch
- 233字
- 2021-07-15 17:34:03
Synchronization
Functions which implement synchronization are prefixed with pthread_rwlock_ or pthread_barrier_. These implement read/write locks and synchronization barriers.
A read/write lock (rwlock) is very similar to a mutex, except that it has the additional feature of allowing infinite threads to read simultaneously, while only restricting write access to a singular thread.
Using rwlock is very similar to using a mutex:
#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t* rwlock, const pthread_rwlockattr_t* attr);
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
In the last code, we include the same general header, and either use the initialization function, or the generic macro. The interesting part is when we lock rwlock, which can be done for just read-only access:
int pthread_rwlock_rdlock(pthread_rwlock_t* rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t* rwlock);
Here, the second variation returns immediately if the lock has been locked already. One can also lock it for write access as follows:
int pthread_rwlock_wrlock(pthread_rwlock_t* rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t * rwlock);
These functions work basically the same, except that only one writer is allowed at any given time, whereas multiple readers can obtain a read-only lock.
Barriers are another concept with Pthreads. These are synchronization objects which act like a barrier for a number of threads. All of these have to reach the barrier before any of them can proceed past it. In the barrier initialization function, the thread count is specified. Only once all of these threads have called the barrier object using the pthread_barrier_wait() function will they continue executing.
- ClickHouse性能之巔:從架構(gòu)設(shè)計(jì)解讀性能之謎
- Visual Basic程序設(shè)計(jì)教程
- 從0到1:HTML+CSS快速上手
- x86匯編語言:從實(shí)模式到保護(hù)模式(第2版)
- Java Web程序設(shè)計(jì)
- 全棧自動(dòng)化測(cè)試實(shí)戰(zhàn):基于TestNG、HttpClient、Selenium和Appium
- RabbitMQ Essentials
- 西門子S7-200 SMART PLC編程從入門到實(shí)踐
- Creating Mobile Apps with jQuery Mobile(Second Edition)
- 基于ARM Cortex-M4F內(nèi)核的MSP432 MCU開發(fā)實(shí)踐
- Extreme C
- SQL Server 2016 從入門到實(shí)戰(zhàn)(視頻教學(xué)版)
- Kotlin Programming By Example
- Scratch從入門到精通
- INSTANT Premium Drupal Themes