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

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.

主站蜘蛛池模板: 海原县| 将乐县| 高邑县| 招远市| 武隆县| 西青区| 亚东县| 高陵县| 新巴尔虎右旗| 繁峙县| 郴州市| 厦门市| 确山县| 宁乡县| 垣曲县| 泸溪县| 石楼县| 溧水县| 皮山县| 芒康县| 灌云县| 安多县| 太仓市| 青海省| 横峰县| 鲜城| 五常市| 龙陵县| 金塔县| 神农架林区| 宁都县| 安平县| 定兴县| 屏山县| 榆树市| 南召县| 汝州市| 临海市| 寿光市| 汪清县| 万盛区|