P
P
polar_winter2015-02-14 12:08:48
OOP
polar_winter, 2015-02-14 12:08:48

How to write MutexLocker correctly?

Created a self-written MutexLocker wrapper, according to RAII.

class pthread_mutex_locker
{
public:
    pthread_mutex_locker(pthread_mutex_wrapper * mu);
    ~pthread_mutex_locker();

private:
    pthread_mutex_wrapper * mutex;
};

I applied my MutexLocker with an anonymous object.
// Тело какой-то функции.
{
 pthread_mutex_locker(&mutex);
//Какой-то код

}

There is a suspicion that the anonymous object is destroyed earlier than necessary and does not protect the code. How do I get it to be destroyed when the function exits. Should MutexLocker be a named object? Are named objects guaranteed to be destroyed on function exit, and not somewhere else?
gcc version 4.8.1 20130909

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Armenian Radio, 2015-02-14
@gbg

Your variant will not work - the mutex will be destroyed immediately after creation. Strictly speaking, in C++ there is no such thing as an "anonymous instance", there is a "temporary instance".
For a named instance, destruction is guaranteed when it goes out of scope - the compound operator {}.

M
Mercury13, 2015-02-14
@Mercury13

pthread_mutex_locker locker (&mutex);
Name it something, and everything will be okay.

D
Dmitry, 2015-02-14
@TrueBers

What's wrong with std::lock_guard?

A
AxisPod, 2015-02-14
@AxisPod

If there is no C++11, take boost::thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question