如何测试自行实现的C++计数信号量?求代码检查指导
信号量实现正确性检查与多线程死锁测试求助
我阅读了Allen B. Downey所著的《Little Book Of Semaphores》,由于信号量仅在C++20中被纳入标准库,因此自行实现了符合书中定义的CountingSemaphore。该实现参考了Stack Overflow上的线程同步问题解答,但存在两处差异:
- 在signal操作中先解锁mutex再通知线程
- 严格遵循书中的信号量定义
目前我仅能完成简单的线程顺序化测试,不清楚如何通过多线程(如100个线程)测试该实现是否存在死锁,同时希望能得到代码正确性检查的帮助。
我的实现代码如下:
semaphore.h
#include <condition_variable> #include <mutex> namespace Semaphore { class CountingSemaphore final { public: explicit CountingSemaphore(int initialValue = 0); void signal(); void wait(); private: std::mutex _mutex{}; std::condition_variable _conditionVar{}; int _value; }; } // namespace Semaphore
semaphore.cpp
#include "semaphore.h" namespace Semaphore { CountingSemaphore::CountingSemaphore(const int initialValue) : _value(initialValue) {} void CountingSemaphore::signal() { std::unique_lock<std::mutex> lock{_mutex}; ++_value; if (0 == _value) { lock.unlock(); _conditionVar.notify_one(); } } void CountingSemaphore::wait() { std::unique_lock<std::mutex> lock{_mutex}; --_value; if (0 > _value) { _conditionVar.wait(lock, [this]() { return (0 <= this->_value); }); } } } // namespace Semaphore
内容的提问来源于stack exchange,提问作者JenyaKh
相关产品推荐
相关产品推荐

