温馨提示×

C++信号量如何用于线程间通信

c++
小樊
86
2024-07-05 19:30:21
栏目: 编程语言

在C++中,信号量可以通过使用std::mutexstd::condition_variable来实现。下面是一个简单的例子,展示了如何使用信号量进行线程间通信。

#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变量用于表示生产者和消费者之间的信号量。生产者生产数据后,会增加semaphore的值并通知消费者;消费者在收到通知后会减少semaphore的值并消费数据。通过std::condition_variable实现了线程之间的通信和同步。

0