#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 共享变量
int count = 0;
// 互斥锁
pthread_mutex_t mutex;
// 线程函数1
void* increment_count(void* arg) {
for (int i = 0; i < 1000000; ++i) {
// 加锁
pthread_mutex_lock(&mutex);
count++;
// 解锁
pthread_mutex_unlock(&mutex);
}
return NULL;
}
// 线程函数2
void* decrement_count(void* arg) {
for (int i = 0; i < 1000000; ++i) {
// 加锁
pthread_mutex_lock(&mutex);
count--;
// 解锁
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
// 创建线程1
if (pthread_create(&thread1, NULL, increment_count, NULL) != 0) {
perror("Failed to create thread 1");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, decrement_count, NULL) != 0) {
perror("Failed to create thread 2");
return 1;
}
// 等待线程1结束
if (pthread_join(thread1, NULL) != 0) {
perror("Failed to join thread 1");
return 1;
}
// 等待线程2结束
if (pthread_join(thread2, NULL) != 0) {
perror("Failed to join thread 2");
return 1;
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
printf("Final count: %d\n", count);
return 0;
}