一、函数约定
1、初始化锁
int pthread_mutex_init(pthread_mutex_t* m, const pthread_mutexattr_t* attr)
2、加锁
int pthread_mutex_lock(pthread_mutex_t* m);
3、解锁
int pthread_mutex_unlock(pthread_mutex_t* m);
4、销毁
int pthread_mutex_destroy(pthread_mutex_t* m);
二、代码如下
#include<pthread.h>
#include<stdio.h>
// 定义结构体变量,代表一个互斥锁
pthread_mutex_t mutex;
// 线程函数,描述线程的逻辑
void* thread_func(void* arg)
{
// 加锁
pthread_mutex_lock(&mutex);
int* total = (int*)arg;
int k;
for(k = 1; k <= 1000; k++){
*total = *total + 1;
}
// 执行一些需要互斥访问的操作
// 转账,修改共享数据
// update("id", "新值");
// 解锁
pthread_mutex_unlock(&mutex);
printf("线程%d计算完毕\n", pthread_self());
return NULL;
}
// pthread库的加锁和解锁操作。
int main()
{// 共享数据
int total = 0;
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
pthread_t t1;
pthread_t t2;
// 创建和启动线程
// 同时建立两个
pthread_create(&t1, NULL, thread_func, &total);
pthread_create(&t2, NULL, thread_func, &total);
// 等待子线程结束
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("计算结果:%d \n", total);
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}