作者:Arthurian 原文鏈接: https://www.cnblogs.com/Arthurian/p/18526135a
在多線程開發(fā)中,經(jīng)常會(huì)遇到數(shù)據(jù)同步,很多情況下用鎖都是一個(gè)很好的選擇。C++中常用的鎖主要有下面幾種:
std::mutex) 1 #include <iostream>
2 #include <mutex>
3 #include <thread>
4
5 std::mutex m;
6 int counter = 0;
7
8 void increment() {
9 m.lock();
10 counter++;
11 std::cout << "Counter value in thread " << std::this_thread::get_id() << " is " << counter << std::endl;
12 m.unlock();
13 }
14
15 int main() {
16 std::thread t1(increment);
17 std::thread t2(increment);
18 t1.join();
19 t2.join();
20 return 0;
21 }
std::recursive_mutex) 1 #include <iostream>
2 #include <mutex>
3 #include <thread>
4
5 std::recursive_mutex rm;
6
7 void recursiveFunction(int count) {
8 rm.lock();
9 if (count > 0) {
10 std::cout << "Recursive call with count = " << count << std::endl;
11 recursiveFunction(count - 1);
12 }
13 rm.unlock();
14 }
15
16 int main() {
17 std::thread t(recursiveFunction, 3);
18 t.join();
19 return 0;
20 }
std::shared_mutex) C++17開始才有 1 #include <iostream>
2 #include <shared_mutex>
3 #include <thread>
4 #include <vector>
5
6 std::shared_mutex smtx;
7 int shared_data = 0;
8
9 void read_data() {
10 std::shared_lock<std::shared_mutex> lock(smtx);
11 std::cout << "Read data: " << shared_data << std::endl;
12 }
13
14 void write_data(int new_value) {
15 std::unique_lock<std::shared_mutex> lock(smtx);
16 shared_data = new_value;
17 std::cout << "Wrote data: " << shared_data << std::endl;
18 }
19
20 int main() {
21 std::vector<std::thread> read_threads;
22 for (int i = 0; i < 5; i++) {
23 read_threads.push_back(std::thread(read_data));
24 }
25 std::thread write_thread(write_data, 10);
26 for (auto& t : read_threads) {
27 t.join();
28 }
29 write_thread.join();
30 return 0;
31 }
std::timed_mutex)std::mutex的擴(kuò)展。除了具備std::mutex的基本功能外,它還允許線程在嘗試獲取鎖時(shí)設(shè)置一個(gè)超時(shí)時(shí)間。 1 #include <iostream>
2 #include <chrono>
3 #include <thread>
4 #include <mutex>
5
6 std::timed_mutex tm;
7
8 void tryLockFunction() {
9 if (tm.try_lock_for(std::chrono::seconds(1))) {
10 std::cout << "Acquired lock" << std::endl;
11 std::this_thread::sleep_for(std::chrono::seconds(2));
12 tm.unlock();
13 } else {
14 std::cout << "Could not acquire lock in time" << std::endl;
15 }
16 }
17
18 int main() {
19 std::thread t1(tryLockFunction);
20 std::thread t2(tryLockFunction);
21 t1.join();
22 t2.join();
23 return 0;
24 }
std::recursive_timed_mutex) 1 #include <iostream>
2 #include <chrono>
3 #include <thread>
4 #include <mutex>
5
6 std::recursive_timed_mutex rtm;
7
8 void recursiveTryLockFunction(int count) {
9 if (rtm.try_lock_for(std::chrono::seconds(1))) {
10 std::cout << "Recursive acquired lock, count = " << count << std::endl;
11 if (count > 0) {
12 recursiveTryLockFunction(count - 1);
13 }
14 rtm.unlock();
15 } else {
16 std::cout << "Could not recursively acquire lock in time" << std::endl;
17 }
18 }
19
20 int main() {
21 std::thread t(recursiveTryLockFunction, 3);
22 t.join();
23 return 0;
24 }
std::atomic_flag實(shí)現(xiàn)) 1 #include <iostream>
2 #include <atomic>
3 #include <thread>
4
5 std::atomic_flag spinLock = ATOMIC_FLAG_INIT;
6
7 void criticalSection() {
8 while (spinLock.test_and_set()) {
9 // 自旋等待
10 }
11 std::cout << "Entered critical section" << std::endl;
12 // 臨界區(qū)操作
13 spinLock.clear();
14 }
15
16 int main() {
17 std::thread t1(criticalSection);
18 std::thread t2(criticalSection);
19 t1.join();
20 t2.join();
21 return 0;
22 }
std::condition_variable)配合互斥鎖用于同步(嚴(yán)格來(lái)說(shuō)條件變量不是鎖,但常一起用于線程同步場(chǎng)景) 1 #include <iostream>
2 #include <thread>
3 #include <mutex>
4 #include <condition_variable>
5 #include <queue>
6
7 std::mutex mtx;
8 std::condition_variable cv;
9 std::queue<int> buffer;
10 const int bufferSize = 5;
11
12 void producer() {
13 for (int i = 0; i < 10; ++i) {
14 std::unique_lock<std::mutex> lock(mtx);
15 while (buffer.size() == bufferSize) {
16 cv.wait(lock);
17 }
18 buffer.push(i);
19 std::cout << "Produced: " << i << std::endl;
20 cv.notify_all();
21 }
22 }
23
24 void consumer() {
25 for (int i = 0; i < 10; ++i) {
26 std::unique_lock<std::mutex> lock(mtx);
27 while (buffer.empty()) {
28 cv.wait(lock);
29 }
30 int data = buffer.front();
31 buffer.pop();
32 std::cout << "Consumed: " << data << std::endl;
33 cv.notify_all();
34 }
35 }
36
37 int main() {
38 std::thread producerThread(producer);
39 std::thread consumerThread(consumer);
40 producerThread.join();
41 consumerThread.join();
42 return 0;
43 }
C++ 校招 / 社招跳槽逆襲!從0到1打造高含金量項(xiàng)目,導(dǎo)師1v1輔導(dǎo),助你斬獲大廠offer!
很多同學(xué)準(zhǔn)備校招時(shí)最焦慮的問(wèn)題就是:“簡(jiǎn)歷沒項(xiàng)目,怎么打動(dòng)面試官?”
為了解決這個(gè)痛點(diǎn),我們推出了 C++訓(xùn)練營(yíng),來(lái)了!

在這里,你可以:
我們不只是教你寫代碼,更帶你走一遍完整的項(xiàng)目流程: 從需求分析、架構(gòu)設(shè)計(jì)、編譯調(diào)試,到版本管理、測(cè)試發(fā)布,全流程掌握!
項(xiàng)目配套資料齊全,遇到問(wèn)題還有導(dǎo)師幫你答疑,不怕卡殼!
項(xiàng)目準(zhǔn)備好了,你只差一次出發(fā)。
相信我,這些項(xiàng)目絕對(duì)能夠讓你進(jìn)步巨大!下面是其中某三個(gè)項(xiàng)目的說(shuō)明文檔

訓(xùn)練營(yíng)適用人群:
不適合人群:

1、C++訓(xùn)練營(yíng),來(lái)了!
2、HarmonyOS 學(xué)習(xí)資料分享(無(wú)套路免費(fèi)分享)
我組建了一些社群一起交流,群里有大牛也有小白,如果你有意可以一起進(jìn)群交流。
歡迎你添加我的微信,我拉你進(jìn)技術(shù)交流群。此外,我也會(huì)經(jīng)常在微信上分享一些計(jì)算機(jī)學(xué)習(xí)經(jīng)驗(yàn)以及工作體驗(yàn),還有一些內(nèi)推機(jī)會(huì)。
加個(gè)微信,打開另一扇窗
感謝你的分享,點(diǎn)贊,在看三連