官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 临猗县| 尖扎县| 安岳县| 阳东县| 武川县| 万宁市| 台安县| 老河口市| 娄烦县| 鲁山县| 南丹县| 达尔| 扬州市| 林口县| 普格县| 织金县| 田阳县| 平和县| 社旗县| 慈溪市| 万荣县| 高台县| 万山特区| 衡南县| 岫岩| 仙桃市| 五家渠市| 来凤县| 泗水县| 博湖县| 武鸣县| 和硕县| 睢宁县| 湛江市| 定西市| 盘山县| 内乡县| 武隆县| 通道| 浑源县| 衡水市|