頭文件
#include <pthread.h>
pthread_mutex_init
函數原型:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
函數參數:
????????mutex
:指向要初始化的互斥量的指針。
????????attr
:指向互斥量屬性對象的指針,若為?NULL
?則使用默認屬性。
函數返回值:
????????成功時返回 0,出錯時返回錯誤碼。
pthread_mutex_lock
函數原型:
int pthread_mutex_lock(pthread_mutex_t *mutex);??
?函數參數:
????????mutex
:指向要鎖定的互斥量的指針。
函數返回值:
????????成功時返回 0,出錯時返回錯誤碼。
pthread_mutex_unlock
函數原型:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
函數參數:
????????mutex
:指向要解鎖的互斥量的指針。
函數返回值:
????????成功時返回 0,出錯時返回錯誤碼。
pthread_mutex_destroy
函數原型:
int pthread_mutex_destroy(pthread_mutex_t *mutex);
函數參數:
????????mutex
:指向要銷毀的互斥量的指針。
函數返回值:
????????成功時返回 0,出錯時返回錯誤碼。
示例
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <semaphore.h>using namespace std;// 線程的安全問題:多線程訪問共享數據,且對共享數據的操作為非原子性操作(不可能被中斷的操作)int tickets = 10; // 總票數pthread_mutex_t lock; // 互斥量對象(鎖)void* thread_handle2(void* data)
{char* name = (char*)data;while (true) {pthread_mutex_lock(&lock);if (tickets > 0) {usleep(1);printf("%s已出票,剩余票數是:%d\n", name, --tickets);}else {printf("%s票已售罄\n", name);break;}pthread_mutex_unlock(&lock);}
}int main()
{pthread_t thread_id;int res = pthread_mutex_init(&lock, NULL); // 互斥量初始化char* s1 = "thread01";char* s2 = "thread02";char* s3 = "thread03";pthread_create(&thread_id, NULL, thread_handle2, s1);pthread_create(&thread_id, NULL, thread_handle2, s2);pthread_create(&thread_id, NULL, thread_handle2, s3);while (true) {}pthread_mutex_destroy(&lock);return 0;
}