溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++多線程庫(kù)函數(shù)并發(fā)控制策略

發(fā)布時(shí)間:2024-09-10 14:53:56 來(lái)源:億速云 閱讀:79 作者:小樊 欄目:編程語(yǔ)言

C++ 多線程庫(kù)提供了一些函數(shù)和類(lèi)來(lái)實(shí)現(xiàn)并發(fā)控制策略,主要包括互斥鎖(mutex)、條件變量(condition variable)和原子操作(atomic operations)等

  1. 互斥鎖(mutex):互斥鎖是最基本的同步機(jī)制,用于保護(hù)共享資源免受多個(gè)線程的同時(shí)訪問(wèn)。當(dāng)一個(gè)線程獲得互斥鎖時(shí),其他線程必須等待該線程釋放鎖后才能繼續(xù)訪問(wèn)共享資源。C++ 標(biāo)準(zhǔn)庫(kù)中的 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;
}
  1. 條件變量(condition variable):條件變量通常與互斥鎖一起使用,以實(shí)現(xiàn)線程間的同步和通信。當(dāng)一個(gè)線程需要等待另一個(gè)線程完成某個(gè)操作時(shí),可以使用條件變量。C++ 標(biāo)準(zhǔn)庫(kù)中的 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;
}
  1. 原子操作(atomic operations):原子操作是一種不可分割的操作,它可以在沒(méi)有鎖的情況下實(shí)現(xiàn)線程安全。C++ 標(biāo)準(zhǔn)庫(kù)中的 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)高效、安全的多線程編程。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

c++
AI