Tsui John
Tsui John

Reputation: 107

C++ Multithread Mutex Lock issue

I am new to C++ & Multithreading. Recently taking a look at the Lock property...

Suppose I have a class with a mutex inside. When I use the lock method on the mutex object, how can I tell which part of the code is blocked/locked? Does it block/lock ALL the member functions inside the class or only the member function in which I triggered the lock?

e.g. (process_data & udf_2)

class data_wrapper
{
private:
    int x;
    some_data data;
    std::mutex m;
public:
    template<typename Function>
    void process_data(Function func)
    {
        std::lock_guard<std::mutex> l(m);
    ......
    }
    void udf_2(int x)
    {
        cout << "Value is " << x; 
    ......
    }
}

=============================

=============================

One more question is that if I saw a template type T, then what's mean by T& and T&&?

Upvotes: 0

Views: 2454

Answers (3)

utnapistim
utnapistim

Reputation: 27365

Using

void process_data(Function func)
{
    std::lock_guard<std::mutex> l(m);
    ......
}

means that any thread that gets to this line, will not return from the constructor of the lock, until any other thread that is past the creation of the lock hasn't exited the scope. In other words, the code represented by you using ellipsis will only be executed by at most one thread at a time, effectively serializing access to the code.

Upvotes: 1

fatihk
fatihk

Reputation: 7919

http://en.cppreference.com/w/cpp/thread/lock_guard

As you can see in the link, std::lock_guard is destructed as soon as the program goes out of scope (e.g. process_data() method ).

lock_guard does not lock all the member variables, but just ones accessed in the scope or process_data()

Upvotes: 1

weima
weima

Reputation: 4902

the mutex doesnt lock your object. mutex provides exclusive access to a part of your program which falls between mutex lock and unlock.

if one thread of your program enters process_data() and is reading some variable, and at the same time another thread enters udf_2() and modifies the same variable, your program is not thread safe. In other words, just using a mutex inside an object is not enough to protect it. You must chanelize access to your variables through methods which are guarded like your method process_data(). only then your program will be thread safe.

I hope i make it clear.

Upvotes: 3

Related Questions