Is it always safe to create a stream and infer the "this" pointer from the constructor?

I got confused with the following code (from Prefer to use active objects instead of a bare topic ):

class Active {
public:

  class Message {        // base of all message types
  public:
    virtual ~Message() { }
    virtual void Execute() { }
  };

private:
  // (suppress copying if in C++)

  // private data
  unique_ptr<Message> done;               // le sentinel
  message_queue< unique_ptr<Message> > mq;    // le queue
  unique_ptr<thread> thd;                // le thread

private:
  // The dispatch loop: pump messages until done
  void Run() {
    unique_ptr<Message> msg;
    while( (msg = mq.receive()) != done ) {
      msg->Execute();
    }
  }

public:
  // Start everything up, using Run as the thread mainline
  Active() : done( new Message ) {
    thd = unique_ptr<thread>(
                  new thread( bind(&Active::Run, this) ) );
  }

...

(After the constructor completion element variables are only available in the element stream).

Can someone explain to me the reasons why in this case it is safe to exchange an Active object thisbetween threads? Do we have any guarantees that the new thread will see the changes made to the constructor before the thread thread line?

+4
source share
2 answers

, ( ) - , .

, Active , , vtable -.

  • vtable, Active . Active , .

  • , , , - . (++ , , , - , .) . thd, , .

  • , , , , , thd. thd, .

  • ( ), .

  • , .

, , .

+2

this, std::thread .

, ( ). std::thread::detach , , Active , undefined.

+1

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


All Articles