What is the best locking mechanism

This forum can be used to talk about general design strategies, new ideas and questions in general related to wxWidgets. If you feel your questions doesn't fit anywhere, put it here.
Post Reply
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7458
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

What is the best locking mechanism

Post by ONEEYEMAN »

Hi, ALL,
I'm trying for the first time create a MT application and I need some help.
If I use std::mutex to lock the object and another thread will try to access it, what will happen?

Lets say I have following:

In thread1:

Code: Select all

int foo()
{
    std::lock_guard<std::mutex>( my_mutex );
    // some operations
    return true;
}
In thread2:

Code: Select all

int bar()
{
    std::lock_guard<std::mutex>( my_mutex );
    // some operations
    return true;
}
So, lets say the first thread is running continuosly and then I call a function in a second thread.

What happen?

If the second thread is trying to acquire the lock in and if it can't will it keep trying until successful? Or the "keep trying" portion is on me?
Or maybe there is a better way of doing it?

Thank you.
Kvaz1r
Super wx Problem Solver
Super wx Problem Solver
Posts: 357
Joined: Tue Jun 07, 2016 1:07 pm

Re: What is the best locking mechanism

Post by Kvaz1r »

Mutex is blocking operation so if one thread is use protected resource all other thread who try to get access to mutex will block until resource won't be unlocked. If anything goes wrong - deadlock.

If you want handle such cases - use try_lock or try_lock_until/try_lock_for from std::timed_mutex.
Post Reply