Home > Enterprise >  shared_timed_mutex not working the way i would expect
shared_timed_mutex not working the way i would expect

Time:12-15

for me, using g , this breaks (hangs forever regardless of what time i put in chrono). but on windows it works fine (sleeps for 1 second):

#include <shared_mutex>
#include <iostream>

int main(int argc, char **argv) {
    std::shared_timed_mutex mut;
    mut.lock();
    std::cout << "before" << std::endl;
    mut.try_lock_shared_for(std::chrono::duration<double>(1));
    std::cout << "after" << std::endl;
}

CodePudding user response:

You are in undefined behavior land so all behavior is correct. You are not allowed to try and lock the mutex in the thread that already owns (has locked) the mutex.

From cppreference:

If try_lock_shared_for is called by a thread that already owns the mutex in any mode (shared or exclusive), the behavior is undefined.

  • Related