2

Is it appropriate to use both a unique_lock and a scoped_lock with the same mutex? To allow for use of cv.wait and optional unlocking while also providing scope-bound safety.

For example;

std::mutex mut;

//thread:

std::condition_variable cv;

std::unique_lock lock(mut);
cv.wait(lock);
std::scoped_lock scopeLock(std::adopt_lock, mut);
lock.release();
//tasks

scopeLock.~scoped_lock();
Mercer
  • 148
  • 1
  • 10
  • 3
    Out of curiosity: Could you elaborate why you would want to do this? The problem I see is that if you do not do `lock.release()`, you will have two `mutex::unlock()` calls which will be undefined behaviour. This kind of counteracts the whole RAII idea; you will still have to do manual cleanup before you can safely exit the scope. – TFM Aug 12 '18 at 08:26
  • @TFM I agree, just lock and unlock the thing yourself. – Paul Sanders Aug 12 '18 at 08:50
  • If you could edit the question to provide a full self-contained example (which we can drop into an IDE and compile), I'm sure the community would be able to demonstrate how to idiomatically achieve what you want. – Richard Hodges Aug 12 '18 at 08:52
  • @TFM So I can unlock it before end of scope but maintain exception safety while it is locked. I've made an edit to the example, I've also been looking for a way to avoid an explicit destructor call. – Mercer Aug 12 '18 at 08:57
  • @Mercer I still don't see the point. `std::unique_lock` too will unlock when it is destroyed. You just don't need the `std::scoped_lock` and especially not the explicit destructor call. – TFM Aug 12 '18 at 09:12
  • 2
    @TFM Understood, I've become used to using scoped locks I'd forgotten their real purpose. I believe I only need a unique_lock and to somehow also use a scoped_lock would provide nothing other than negative side effects. Thanks. – Mercer Aug 12 '18 at 09:19

0 Answers0