头文件
#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;
}