您好,登錄后才能下訂單哦!
C++ 標(biāo)準(zhǔn)庫中的線程同步庫提供了一組原語,用于在多線程環(huán)境中實(shí)現(xiàn)數(shù)據(jù)共享和保護(hù)
std::mutex
是 C++ 中最基本的同步原語之一。它提供了一種方法來保護(hù)共享數(shù)據(jù),以防止多個(gè)線程同時(shí)訪問。當(dāng)一個(gè)線程鎖定互斥鎖時(shí),其他試圖鎖定該互斥鎖的線程將被阻塞,直到鎖被解鎖。
示例:
#include<iostream>
#include<thread>
#include <mutex>
std::mutex mtx; // 全局互斥鎖
int shared_data = 0; // 共享數(shù)據(jù)
void thread_function() {
std::unique_lock<std::mutex> lock(mtx); // 鎖定互斥鎖
++shared_data; // 修改共享數(shù)據(jù)
lock.unlock(); // 解鎖互斥鎖
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
std::cout << "Shared data: "<< shared_data<< std::endl;
return 0;
}
std::recursive_mutex
類似于 std::mutex
,但允許同一線程多次鎖定相同的互斥鎖。這在某些情況下可能很有用,例如在遞歸函數(shù)中保護(hù)共享數(shù)據(jù)。
std::chrono
是 C++ 中處理時(shí)間的庫,它提供了高精度時(shí)間測(cè)量和時(shí)間點(diǎn)操作。這對(duì)于實(shí)現(xiàn)超時(shí)鎖定和定時(shí)任務(wù)非常有用。
std::condition_variable
是一個(gè)同步原語,允許一個(gè)或多個(gè)線程等待某個(gè)條件成立。當(dāng)條件成立時(shí),線程將被喚醒并繼續(xù)執(zhí)行。條件變量通常與互斥鎖一起使用,以確保線程安全地訪問共享數(shù)據(jù)。
示例:
#include<iostream>
#include<thread>
#include <mutex>
#include<condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false; // 共享數(shù)據(jù)
void print_id() {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) { // 如果 ready 為 false,則等待
cv.wait(lck); // 當(dāng)前線程被阻塞,并釋放鎖
}
std::cout << "Thread "<< std::this_thread::get_id() << " is ready\n";
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true; // 修改共享數(shù)據(jù)
cv.notify_all(); // 喚醒所有等待的線程
}
int main() {
std::thread threads[10];
for (auto &th : threads) {
th = std::thread(print_id);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
go(); // 修改 ready 并喚醒所有線程
for (auto &th : threads) {
th.join();
}
return 0;
}
std::shared_mutex
是一種特殊類型的互斥鎖,允許多個(gè)線程同時(shí)讀取共享數(shù)據(jù),但只允許一個(gè)線程寫入。這在讀操作遠(yuǎn)多于寫操作的場(chǎng)景中非常有用,因?yàn)樗梢蕴岣咝阅堋?/p>
std::atomic
是一種特殊類型的變量,支持無鎖編程。原子操作是不可分割的,這意味著它們?cè)诙嗑€程環(huán)境中是線程安全的。原子操作通常比使用互斥鎖更高效,但它們的功能有限,只支持基本的算術(shù)和邏輯操作。
C++11 引入了 thread_local
關(guān)鍵字,用于聲明線程局部變量。線程局部變量在每個(gè)線程中都有自己的實(shí)例,因此它們不需要同步。這可以用于存儲(chǔ)每個(gè)線程的狀態(tài)信息或緩存數(shù)據(jù)。
總之,C++ 標(biāo)準(zhǔn)庫提供了一組強(qiáng)大的同步原語,可以幫助開發(fā)人員在多線程環(huán)境中實(shí)現(xiàn)高效、安全的數(shù)據(jù)共享和保護(hù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。