两个线程实现同步代码示例
int counter = 0;
pthread_mutex_t mutex;
// 线程1递增计数器的函数
void *thread_increment(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
// 线程2递减计数器的函数
void *thread_decrement(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
counter--;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t threads[THREAD_COUNT];
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
// 创建线程1
if (pthread_create(&threads[0], NULL, thread_increment, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 创建线程2
if (pthread_create(&threads[1], NULL, thread_decrement, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 等待所有线程执行完毕
for (int i = 0; i < THREAD_COUNT; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
// 打印最终的计数器值
printf("Final counter value: %d\n", counter);
return 0;
}