Linux c++ 信号量
时间: 2024-01-28 20:12:11 浏览: 94
C++信号量使用
Linux C++中的信号量可以使用mutex和condition_variable实现。具体实现方法如下:
1.定义一个信号量类,包含一个互斥量和一个条件变量:
```c++
#include <mutex>
#include <condition_variable>
class Semaphore {
public:
Semaphore(int count = 0) : count_(count) {}
void notify() {
std::unique_lock<std::mutex> lock(mutex_);
++count_;
cv_.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
while(count_ == 0) {
cv_.wait(lock);
}
--count_;
}
private:
std::mutex mutex_;
std::condition_variable cv_;
int count_;
};
```
2.在需要使用信号量的地方,创建一个Semaphore对象,调用wait()方法等待信号量,调用notify()方法释放信号量:
```c++
Semaphore sem(0);
// 线程1
void thread1() {
// do something
sem.notify();
}
// 线程2
void thread2() {
sem.wait(); // do something
}
```
3.使用信号量实现生产者消费者模型:
```c++
#include <iostream>
#include <thread>
#include <vector>
class Semaphore {
public:
Semaphore(int count = 0) : count_(count) {}
void notify() {
std::unique_lock<std::mutex> lock(mutex_);
++count_;
cv_.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
while(count_ == 0) {
cv_.wait(lock);
}
--count_;
}
private:
std::mutex mutex_;
std::condition_variable cv_;
int count_;
};
Semaphore sem_empty(10); // 缓冲区空闲信号量
Semaphore sem_full(0); // 缓冲区满信号量
std::vector<int> buffer; // 缓冲区
void producer() {
for(int i = 0; i < 100; ++i) {
sem_empty.wait();
buffer.push_back(i);
sem_full.notify();
}
}
void consumer() {
for(int i = 0; i < 100; ++i) {
sem_full.wait();
int data = buffer.back();
buffer.pop_back();
sem_empty.notify();
std::cout << "consume data: " << data << std::endl;
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
```
阅读全文