#include <stdio.h>
#include <pthread.h>
// 定义共享资源
int shared_variable = 0;
// 定义互斥锁
pthread_mutex_t mutex;
// 线程函数
void* increment(void* arg) {
for (int i = 0; i < 100; ++i) {
// 加锁
pthread_mutex_lock(&mutex);
shared_variable++;
// 解锁
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
pthread_t thread1, thread2;
// 创建线程
pthread_create(&thread1, NULL, increment, NULL);
pthread_create(&thread2, NULL, increment, NULL);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
printf("Final value of shared variable: %d\n", shared_variable);
return 0;
}
- 共享资源定义:定义了一个全局整型变量
shared_variable
作为共享资源。
- 互斥锁定义:定义了一个
pthread_mutex_t
类型的互斥锁mutex
。
- 线程函数
increment
:
- 在循环中,每次对共享资源
shared_variable
进行递增操作前,使用pthread_mutex_lock
加锁。
- 递增操作完成后,使用
pthread_mutex_unlock
解锁。
main
函数:
- 使用
pthread_mutex_init
初始化互斥锁。
- 创建两个线程,每个线程都执行
increment
函数。
- 使用
pthread_join
等待两个线程执行完毕。
- 使用
pthread_mutex_destroy
销毁互斥锁。
- 最后输出共享资源
shared_variable
的最终值。