手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

linux线程互斥锁的使用方法及代码测试

时间:2024-10-12 14:40:34

1、编辑调试代码#include <stdio.h>#include 争犸禀淫<pthread.h>int global_val = 0;void *thread1(void *arg){ while(1){ global_val = global_val + 1; printf("thread1 global_val=%d\n", global_val); global_val = global_val + 1; usleep(100); printf("thread1 global_val=%d\n", global_val); usleep(100); } return NULL;}void *thread2(void *arg){ while(1){ global_val = global_val + 1; printf("thread2 global_val=%d\n", global_val); usleep(100); global_val = global_val + 1; printf("thread2 global_val=%d\n", global_val); usleep(100); } return NULL;}

linux线程互斥锁的使用方法及代码测试

2、编译测试代码gcc mutex.c -o mutex -lpthread

linux线程互斥锁的使用方法及代码测试

3、查看运行结果,图示位置发现问题。结果不正确。

linux线程互斥锁的使用方法及代码测试

4、上述代码是无锁状态下的运行情况,运行结果与预期的结果不同,出现错误。下面我们加上互斥锁。#include <stdio.h>#include <pthread.h>pthread_mutex_t thread_mutex;int global_val = 0;void *thread1(void *arg){ while(1){ pthread_mutex_lock(&thread_mutex); global_val = global_val + 1; printf("thread1 global_val=%d\n", global_val); global_val = global_val + 1; usleep(100); printf("thread1 global_val=%d\n", global_val); usleep(100); pthread_mutex_unlock(&thread_mutex); } return NULL;}void *thread2(void *arg){ while(1){ pthread_mutex_lock(&thread_mutex); global_val = global_val + 1; printf("thread2 global_val=%d\n", global_val); usleep(100); global_val = global_val + 1; printf("thread2 global_val=%d\n", global_val); usleep(100); pthread_mutex_unlock(&thread_mutex); } return NULL;}int main(void){ pthread_t thread_id1 = 0, thread_id2 = 0; pthread_mutex_init(&thread_mutex, NULL); pthread_create(&thread_id1, NULL, thread1, NULL); pthread_create(&thread_id2, NULL, thread2, NULL); pthread_join(thread_id1, NULL); pthread_join(thread_id2, NULL); return 0;}

linux线程互斥锁的使用方法及代码测试

5、保存代码后编译。

linux线程互斥锁的使用方法及代码测试

6、运行查看结果,与预期的一致。说明互斥锁起到保护临界资源的作用。

linux线程互斥锁的使用方法及代码测试
© 手抄报圈