Can mutexes ensure the visibility of objects until they explicitly protect them?

Given the following code, is it possible that threads can see the state of an object in different ways, despite the fact that they both refer to 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 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? Are mutexes capable of caching? Mutexes have more functionality than memory barriers with atomics?

+4
source share
1 answer

Given the following code, is it possible that threads can see the state of an object in different ways , despite the fact that they both refer to the same pointer?

Answer: No.

: , .

dummy , , . , , ( , ), .

. , DummyObject .

§1.10.7:

, , .

...

, , , , . , , , .

+8

Source: https://habr.com/ru/post/1626839/


All Articles