您好,登錄后才能下訂單哦!
C++ 多線程庫(kù)提供了一些函數(shù)和類(lèi)來(lái)實(shí)現(xiàn)并發(fā)控制策略,主要包括互斥鎖(mutex)、條件變量(condition variable)和原子操作(atomic operations)等
std::mutex
類(lèi)提供了互斥鎖的實(shí)現(xiàn)。示例代碼:
#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::condition_variable
類(lèi)提供了條件變量的實(shí)現(xiàn)。示例代碼:
#include<iostream>
#include<thread>
#include <mutex>
#include<condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false; // 共享狀態(tài)
void worker_thread() {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) { // 如果共享狀態(tài)為 false,則等待
cv.wait(lock);
}
std::cout << "Worker thread is ready."<< std::endl;
}
void main_thread() {
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模擬延遲
{
std::unique_lock<std::mutex> lock(mtx);
ready = true; // 修改共享狀態(tài)
}
cv.notify_one(); // 喚醒等待的線程
}
int main() {
std::thread worker(worker_thread);
main_thread();
worker.join();
return 0;
}
std::atomic
類(lèi)模板提供了原子操作的實(shí)現(xiàn)。原子操作通常用于實(shí)現(xiàn)無(wú)鎖數(shù)據(jù)結(jié)構(gòu)和高性能的并發(fā)算法。示例代碼:
#include<iostream>
#include<thread>
#include<atomic>
std::atomic<int> shared_data(0); // 原子整數(shù)類(lèi)型的共享數(shù)據(jù)
void thread_function() {
++shared_data; // 原子操作,自增 1
}
int main() {
std::thread t1(thread_function);
std::thread t2(thread_function);
t1.join();
t2.join();
std::cout << "Shared data: "<< shared_data.load()<< std::endl;
return 0;
}
這些并發(fā)控制策略可以根據(jù)具體的應(yīng)用場(chǎng)景和需求進(jìn)行組合使用,以實(shí)現(xiàn)高效、安全的多線程編程。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。