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

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.

主站蜘蛛池模板: 来凤县| 台北市| 甘泉县| 疏勒县| 和硕县| 恩平市| 金坛市| 台东县| 儋州市| 通河县| 榕江县| 安福县| 乌兰浩特市| 扎兰屯市| 伊金霍洛旗| 年辖:市辖区| 双牌县| 崇文区| 常熟市| 安仁县| 千阳县| 青浦区| 宜春市| 隆回县| 咸阳市| 沿河| 芦溪县| 平原县| 桓台县| 犍为县| 隆昌县| 自贡市| 古田县| 仪征市| 象山县| 容城县| 拜城县| 民乐县| 郸城县| 阜宁县| 崇信县|