溫馨提示×

C++信號量如何用于線程間通信

c++
小樊
88
2024-07-05 19:30:21
欄目: 編程語言

在C++中,信號量可以通過使用std::mutexstd::condition_variable來實現(xiàn)。下面是一個簡單的例子,展示了如何使用信號量進行線程間通信。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int semaphore = 0;

void producer() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        
        // Produce some data
        
        semaphore++;
        cv.notify_one();
        
        lock.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        
        cv.wait(lock, []{ return semaphore > 0; });
        
        // Consume the data
        
        semaphore--;
        
        lock.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    std::thread producerThread(producer);
    std::thread consumerThread(consumer);
    
    producerThread.join();
    consumerThread.join();
    
    return 0;
}

在上面的例子中,semaphore變量用于表示生產(chǎn)者和消費者之間的信號量。生產(chǎn)者生產(chǎn)數(shù)據(jù)后,會增加semaphore的值并通知消費者;消費者在收到通知后會減少semaphore的值并消費數(shù)據(jù)。通過std::condition_variable實現(xiàn)了線程之間的通信和同步。

0