title: Passing messages between threads and memory management
body: <p>I'm writing a C++ application with two threads. Thread A will send messages to thread B. The message type could be:</p>
  
  <pre><code>struct MyMessageType
  {
    int a;
    enum MyEnum b;
    bool someFlag;
  }
  </code></pre>
  
  <p>A <code>std::queue&lt;MyMessageType&gt; messageQueue</code> is shared between the threads for passing messages.</p>
  
  <p>In the sending thread, I'll have something like:</p>
  
  <pre><code>struct MyMessageType newMessage;
  newMessage.a = 14;
  newMessage.b = someEnumeratedValue;
  newMessage.someFlag = false;
  GrabTheMutexProtectingTheQueue();
  messageQueue.push(newMessage);
  ReleaseTheMutexProtectingTheQueue();
  </code></pre>
  
  <p>My question is regarding memory management, and is twofold:</p>
  
  <p>A) How do I ensure that the pointer to <code>newMessage</code> is valid when the receiving thread gets the message? What would happen, for instance, if the function that created <code>newMessage</code> ended and <code>newMessage</code> therefore went out of scope before the receiving thread processed the message?</p>
  
  <p>B) Once I can ensure that the <code>newMessage</code> pointer is valid when the receiving thread processes it, how to I free up the memory that was used by the struct?</p>