Reputation: 71
I have the following code example and I'm not sure if it is thread safe.
void remove(/*...*/) {
int a;
float* data;
while (true)
{
unique_lock<mutex> lock1(mu);
cond.wait(lock1, [this](){return count > 0;});
lock1.unlock();
a = std_queue1.front();
data = std_queue2.front();
// process data
unique_lock<mutex> lock2(mu);
std_queue1.pop();
std_queue2.pop();
count--;
lock2.unlock();
cond.notify_all();
}
}
void add(/*...*/){
int a, iterations = 0;
vector<float*> data;
// Allocate some data entries
while (true) {
// set a
unique_lock<mutex> lock1(mu);
std_queue1.push(a);
cond.wait(lock1, [this, &limit]() { return count < limit; });
lock1.unlock();
// Init data
if (iterations++ > 2) {
unique_lock<mutex> lock2(mu);
std_queue2.push(data[/*...*/]);
count++;
lock2.unlock();
cond.notify_all();
}
}
}
remove(...) and add(...) are functions of the same class. Each function is executed by one thread and both Threads access the same queues. A mutex is locked to push and pop data of the queues, but not for the function front().
So my question is: Is this example thread safe? Or do I need a mutex for the front() function? And is the mutex necessary for the functions pop() and push()?
Upvotes: 0
Views: 146
Reputation: 238311
So my question is: Is this example thread safe?
No.
Or do I need a mutex for the front() function?
Yes.
And is the mutex necessary for the functions pop() and push()?
Yes.
Modifying a standard container is not guaranteed to be thread safe.
Upvotes: 2