随着任务的添加,将会面临多线程编程。多线程编程可以提高任务的执行效率,但是面临的问题是线程之间共享资源的保护问题,做好临界资源的互斥。如果稍不注意,看似没问题的代码,运行之后就可以看到问题之所在。下面就从无锁的状态下代码的运行结果和加上互斥锁之后运行的结果对比。
工具/原料
方法/步骤
1编辑调试代码#include #include 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;}
2编译测试代码gcc mutex.c -o mutex -lpthread
4上述代码是无锁状态下的运行情况,运行结果与预期的结果不同,出现错误。下面我们加上互斥锁。#include #include 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;}
6运行查看结果,与预期的一致。说明互斥锁起到保护临界资源的作用。
注意事项