I am confused with the following code (from Prefer Using Active Objects Instead of Naked Threads):
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 constructor completion member variables are accessed only in the member thread).
Could somebody explain me the reasons why in this case it is safe to share Active object's this
between threads? Do we have any guarantees that the new thread will see the changes made in the constructor before the thread spawn line?