Considering the following code, is it possible that the threads may see the state of an object differently, despite they both refer by the same pointer?
using namespace std;
class ProducerAndConsumer{
class DummyObject {
public:
DummyObject() {
sprintf(a, "%d", rand());
}
private:
char a[1000];
};
mutex queue_mutex_;
queue<DummyObject *> queue_;
thread *t1, *t2;
void Produce() {
while (true) {
Sleep(1);
// constructing object without any explicit synchronization
DummyObject *dummy = new DummyObject();
{
lock_guard<mutex> guard(queue_mutex_);
if (queue_.size() > 1000) {
delete dummy;
continue;
}
queue_.push(dummy);
}
}
}
void Consume() {
while (true) {
Sleep(1);
DummyObject *dummy;
{
lock_guard<mutex> guard(queue_mutex_);
if (queue_.empty())
continue;
dummy = queue_.front();
queue_.pop();
}
// Do we have dummy object's visibility issues here?
delete dummy;
}
}
public:
ProducerAndConsumer() {
t1 = new thread(bind(&ProducerAndConsumer::Consume, this));
t2 = new thread(bind(&ProducerAndConsumer::Produce, this));
}
};
Could you say that this example is thread safe? Do mutexes enforce cache trashing? Do mutexes provide more functionality than memory barriers together with atomics?