You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试自行实现的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:18:13