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;
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?
source
share