Simple Mutex ever. Does this example work? Is it thread safe?

I would like to ask about the simplest Mutex approach for multithreading. Is the following code safe for threads (fast n-dirty)?

class myclass
{
    bool locked;
    vector<double> vals;

    myclass();
    void add(double val);
};

void myclass::add(double val)
{
    if(!locked)
    {
        this->locked = 1;
        this->vals.push_back(val);
        this->locked = 0;
    }
    else
    {
        this->add(val);
    }
}

int main()
{
    myclass cls;
    //start parallelism
    cls.add(static_cast<double>(rand()));
}

It works? Is it thread safe? I'm just trying to figure out how to write a simple mutex.

If you have any advice on my example, it would be nice.

Thank.

Thank you for not working. Can you suggest a compiler independent fix?

+5
source share
6 answers

Is it thread safe?

. , ; , . (, , .)

, . ++ 11 ​​:

std::atomic_flag locked;

if (!locked.test_and_set()) {
    vals.push_back(val);
    locked.clear();
} else {
    // I don't know exactly what to do here; 
    // but recursively calling add() is a very bad idea.
}

:

std::mutex mutex;

std::lock_guard<std::mutex> lock(mutex);
vals.push_back(val);

, /, , .

+8

, .

if(!locked)

this->locked = 1;

, . test and set mutex.

+5

vals. :

//<<< Suppose it 0
if(!locked)
{   //<<< Thread 0 passes the check
    //<<< Context Switch - and Thread 1 is also there because locked is 0
    this->locked = 1;
    //<<< Now it possible for one thread to be scheduled when another one is in
    //<<< the middle of modification of the vector
    this->vals.push_back(val);
    this->locked = 0;
}
+5

? -?

. .

, :

if(!locked)
{
    this->locked = 1;

... .

, , . SO-.

+2

, .

, myclass::add . , .locked false.

:

if(!locked)
{

, . .

, , , !locked if.

vals.push_back() .

Boom.

+2

, , . : , .

nitty gritty ( - , ), .

+1
source

All Articles