Home > front end >  `std::lock_guard` for `std::counting_semaphore` and `std::binary_semaphore`
`std::lock_guard` for `std::counting_semaphore` and `std::binary_semaphore`

Time:08-24

Is there any RAII guard similar to std::lock_guard, std::scoped_lock or std::unique_lock provided by the standard which I can use in combination with std::binary_semaphore and std::counting_semaphore?

CodePudding user response:

In contrast to a std::mutex, the acquire and release call of a std::counting_semaphore can happen on different threads. So, I think it is not the main use case of a semaphore to be locked and unlocked in the same scope. However, you can easily create your custom lock_guard like this:

#include <semaphore>
#include <iostream>

template <typename T>
class custom_lock_guard
{
    T &m_;

public:
    custom_lock_guard(T &m) : m_(m)
    {
        m_.acquire();
        std::cout << "Lock acquired" << std::endl;
    }
    ~custom_lock_guard()
    {
        m_.release();
        std::cout << "Lock released" << std::endl;
    }
};

std::counting_semaphore<10> m(5);
std::binary_semaphore n(1);

int main()
{
    custom_lock_guard g(m);
    custom_lock_guard h(n);

    return 0;
}

CodePudding user response:

You'll have to wait until std::experimental::scope_exit is supported. Then you can write this:

{
  m.acquire();
  auto guard = std::experimental::scope_exit([&]{m.release();});
  // other stuff...
}

Until then you'll have to settle from a custom implementation.

  • Related