c++11中使用了std::lock_guard互斥锁(#include <thread>)。还有一种,我们看看#include <pthread.h>中使用方法。(自我理解锁的范围可随意控制)
操作函数
pthread_mutex_t lock; /* 互斥锁定义 */ pthread_mutex_init(&lock, NULL); /* 动态初始化, 成功返回0,失败返回非0 */ pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER; /* 静态初始化 */ pthread_mutex_lock(&lock); /* 阻塞的锁定互斥锁 */ pthread_mutex_trylock(&thread_mutex);/* 非阻塞的锁定互斥锁,成功获得互斥锁返回0,如果未能获得互斥锁,立即返回一个错误码 */ pthread_mutex_unlock(&lock); /* 解锁互斥锁 */ pthread_mutex_destroy(&lock) /* 销毁互斥锁 */
Example
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> static pthread_mutex_t g_mutex_lock; static int g_count = 0; static void *thread_fun_1(void *data) { pthread_mutex_lock(&g_mutex_lock); g_count++; printf("%s g_count: %d ", __func__, g_count); pthread_mutex_unlock(&g_mutex_lock); } static void *thread_fun_2(void *data) { pthread_mutex_lock(&g_mutex_lock); g_count++; printf("%s g_count: %d ", __func__, g_count); pthread_mutex_unlock(&g_mutex_lock); } static void *thread_fun_3(void *data) { pthread_mutex_lock(&g_mutex_lock); g_count++; printf("%s g_count: %d ", __func__, g_count); pthread_mutex_unlock(&g_mutex_lock); } int main(int argc, char const *argv[]) { int ret; pthread_t pid[3]; ret = pthread_mutex_init(&g_mutex_lock, NULL); if (ret != 0) { printf("mutex init failed "); return -1; } pthread_create(&pid[0], NULL, thread_fun_1, NULL); pthread_create(&pid[1], NULL, thread_fun_2, NULL); pthread_create(&pid[2], NULL, thread_fun_3, NULL); pthread_join(pid[0], NULL); pthread_join(pid[1], NULL); pthread_join(pid[2], NULL); pthread_mutex_destroy(&g_mutex_lock); return 0; }