本文主要是介绍【CPP】多线程并发—— Mutex 和 Lock,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <iostream>
#include <thread>
#include <mutex>
#include "my_utils.h"std::mutex mtx; // 全局互斥锁
int shared_data = 0; // 共享数据 void increment() { for (int i = 0; i < 10; ++i) { std::cout <<"increment lock_guard: "<<"\n";std::lock_guard<std::mutex> lock(mtx); // 在这里锁定互斥锁 ++shared_data; std::cout <<"increment: "<<shared_data<<"\n";SLEEP_FOR_500_MS();} SLEEP_FOR_500_MS();for (int i = 0; i < 10; ++i) { std::cout <<"increment lock_guard: "<<"\n";std::lock_guard<std::mutex> lock(mtx); // 在这里锁定互斥锁 ++shared_data; std::cout <<"increment: "<<shared_data<<"\n";SLEEP_FOR_500_MS();}
} void decrement() { for (int i = 0; i < 10; ++i) { std::cout <<"decrement lock_guard1: "<<"\n";std::lock_guard<std::mutex> lock(mtx); // 在这里锁定互斥锁 --shared_data; SLEEP_FOR_500_MS();std::cout <<"decrement: "<<shared_data<<"\n";} for (int i = 0; i < 10; ++i) { std::cout <<"decrement lock_guard2: "<<"\n";std::lock_guard<std::mutex> lock(mtx); // 在这里锁定互斥锁 --shared_data; SLEEP_FOR_500_MS();std::cout <<"decrement: "<<shared_data<<"\n";}
} int main() { std::thread t1(increment); std::thread t2(decrement); std::cout << "task inited: " << shared_data << std::endl; t1.join(); t2.join(); std::cout << "Final value of shared_data: " << shared_data << std::endl; return 0;
}
运行结果如下:
increment lock_guard:
increment: 1
task inited: 1
decrement lock_guard1:
increment lock_guard:
increment: 2
increment lock_guard:
decrement: 1
decrement lock_guard1:
decrement: 0
decrement lock_guard1:
decrement: -1
decrement lock_guard1:
decrement: -2
decrement lock_guard1:
decrement: -3
decrement lock_guard1:
decrement: -4
decrement lock_guard1:
decrement: -5
decrement lock_guard1:
decrement: -6
decrement lock_guard1:
decrement: -7
decrement lock_guard1:
decrement: -8
decrement lock_guard2:
decrement: -9
decrement lock_guard2:
decrement: -10
decrement lock_guard2:
decrement: -11
decrement lock_guard2:
decrement: -12
decrement lock_guard2:
decrement: -13
decrement lock_guard2:
decrement: -14
decrement lock_guard2:
decrement: -15
decrement lock_guard2:
decrement: -16
decrement lock_guard2:
decrement: -17
decrement lock_guard2:
decrement: -18
increment: -17
increment lock_guard:
increment: -16
increment lock_guard:
increment: -15
increment lock_guard:
increment: -14
increment lock_guard:
increment: -13
increment lock_guard:
increment: -12
increment lock_guard:
increment: -11
increment lock_guard:
increment: -10
increment lock_guard:
increment: -9
increment lock_guard:
increment: -8
increment lock_guard:
increment: -7
increment lock_guard:
increment: -6
increment lock_guard:
increment: -5
increment lock_guard:
increment: -4
increment lock_guard:
increment: -3
increment lock_guard:
increment: -2
increment lock_guard:
increment: -1
increment lock_guard:
increment: 0
Final value of shared_data: 0
这篇关于【CPP】多线程并发—— Mutex 和 Lock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!