简体   繁体   中英

exception thrown from std::scoped_lock

I am attempting to lock a mutex from another thread, to clear a vector, using a scoped_lock, expecting that the code will wait until the other thread releases it.

But what happens, is that the function which attempts to acquire the lock throws an exception, stating that the resource is busy.

//Called from thread 1
Foo::DoStuff()
{
    std::scoped_lock<std::mutex>(m_lock);
    for (auto thing: stuff) //should be non trivial in size
    {
        thing->bar();
    }
}

//called from thread 0
Foo::ClearStuff()
{
    try
    {
        std::scoped_lock<std::mutex>(m_lock); //throws 
        stuff.clear();
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        // device or resource busy: device or resource busy
    }
}

My threading knowledge is based on the SDL2 threading library, so I'm not sure what I am doing wrong. Am I using the wrong thread construct? If so, what should I be using to ensure that the call waits until the mutex is freed?

You need to store the scoped lock. As it is, the lock is acquired into a temporary variable which is immediately destroyed, releasing the lock.

std::scoped_lock<std::mutex> lock(m_lock);

Side note: Instead of m_lock , I would have called it m_stuff_mtx since it controls access to stuff , is a mutex and there are other things in play called locks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM