C++ 多线程互斥锁(mutex,lock,lock_guard) Posted on 2022-03-22 | In dev , c++ | [TOC] 源代码12345678910111213141516171819202122232425262728293031323334#include <iostream>#include <thread>void work1(int& sum) { for (int i = 1; i < 5000; i++) { sum += i; }}void work2(int& sum) { for (int i = 5000; i <= 10000; i++) { sum += i; }}int fun() { int sum = 0; for (int i = 1; i <= 10000; i++) { sum += i; } return sum;}int main(){ int ans = 0; std::thread t1(work1, std::ref(ans)); std::thread t2(work2, std::ref(ans)); t1.join(); t2.join(); std::cout << "sum1 : " << ans << std::endl; std::cout << "sum2 : " << fun() << std::endl; return 0;} 第一实现 mutex参数lock, unlock12345678910111213141516171819202122232425262728293031323334353637383940#include <iostream>#include <thread>#include <mutex>void work1(int& sum, std::mutex& mylock) { for (int i = 1; i < 5000; i++) { mylock.lock(); sum += i; mylock.unlock(); }}void work2(int& sum, std::mutex& mylock) { for (int i = 5000; i <= 10000; i++) { mylock.lock(); sum += i; mylock.unlock(); }}int fun() { int sum = 0; for (int i = 1; i <= 10000; i++) { sum += i; } return sum;}int main(){ std::mutex mylock; int ans = 0; std::thread t1(work1, std::ref(ans), std::ref(mylock)); std::thread t2(work2, std::ref(ans), std::ref(mylock)); t1.join(); t2.join(); std::cout << "sum1 : " << ans << std::endl; std::cout << "sum2 : " << fun() << std::endl; return 0;} 第二种 lock_guard类模板1234567891011121314151617181920212223242526272829303132333435363738#include <iostream>#include <thread>#include <mutex>void work1(int& sum, std::mutex& mylock) { for (int i = 1; i < 5000; i++) { std::lock_guard<std::mutex> mylock_guard(mylock); sum += i; }}void work2(int& sum, std::mutex& mylock) { for (int i = 5000; i <= 10000; i++) { std::lock_guard<std::mutex> mylock_guard(mylock); sum += i; }}int fun() { int sum = 0; for (int i = 1; i <= 10000; i++) { sum += i; } return sum;}int main(){ std::mutex mylock; int ans = 0; std::thread t1(work1, std::ref(ans), std::ref(mylock)); std::thread t2(work2, std::ref(ans), std::ref(mylock)); t1.join(); t2.join(); std::cout << "sum1 : " << ans << std::endl; std::cout << "sum2 : " << fun() << std::endl; return 0;} https://cloud.tencent.com/developer/article/1583894