请利用c++编程 利用记录型信号量和AND型信号量实现生产者和消费者进程之间的同步
时间: 2024-10-22 07:15:06 浏览: 26
在C++中,我们可以使用互斥量、条件变量以及记录型信号量(semaphore array)和AND型信号量来实现生产者-消费者(Producer-Consumer)问题的同步。这个经典问题是操作系统中资源管理的一个例子,涉及到两个进程,一个是生产者,负责生成产品放入缓冲区;另一个是消费者,负责从缓冲区取走并消费产品。
首先,我们需要包含必要的头文件,并定义一些共享数据结构:
```cpp
#include <iostream>
#include <thread>
#include <mutex> // std::mutex for locking and unlocking
#include <condition_variable> // std::condition_variable for signaling and waiting
#include <vector> // std::vector to store products
std::mutex mtx; // Mutex for mutual exclusion
std::condition_variable cv_prod; // For producer signaling
std::condition_variable cv_cons; // For consumer signaling
int available = 0; // Record-type semaphore (number of available items)
int total_items = 0; // AND-type semaphore (total items produced)
// Buffer size
const int BUFFER_SIZE = 5;
```
然后定义生产者和消费者的函数:
```cpp
void producer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv_prod.wait(lock, []{ return available < BUFFER_SIZE; }); // Wait until there's space in the buffer
// Produce an item and increment
++total_items;
available++;
std::cout << "Producer produced an item, now total is: " << total_items << std::endl;
lock.unlock();
cv_cons.notify_one(); // Signal consumer that a new product is available
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv_cons.wait(lock, []{ return total_items > 0; }); // Wait until there's something to consume
if (available > 0) { // Consume an item and decrement
--total_items;
available--;
}
std::cout << "Consumer consumed an item, now total is: " << total_items << std::endl;
lock.unlock();
cv_prod.notify_one(); // Notify producer that consumption has finished
}
}
```
最后,在主函数中启动生产者和消费者线程:
```cpp
int main() {
std::thread producer_thread(producer);
std::thread consumer_thread(consumer);
producer_thread.join();
consumer_thread.join();
return 0;
}
```
阅读全文