title: C++ Sharing non blocking queue and mutex between two detached threads
body: <p>I'm trying to learn std::thread in C++ today. My goal is to spawn two threads, one a network listener, and the other a network transmitter.  The listener will get feedback messages from the destination server and then send commands to the transmitter through a shared queue (non blocking). I'm a little confused about the proper way to share the queue.  </p>
  
  <p>I have a class called Network that contains everything for the above, here's part of it.</p>
  
  <pre><code>//part of my class
  
  std::mutex mMessageMutex;
  
  //message is class for messages to share
  queue&lt;message&gt; mMessageQueue; 
  
  std::thread mTCPthread;
  std::thread mUDPthread;
  
  Network::threadTest(){
      mTCPthread =  std::thread(&amp;Sender::tcpThread, this);
      mUDPthread =  std::thread(&amp;Sender::udpThread, this);
      mTCPthread.detach();
      mUDPthread.detach();
  
  }
  
  Network::tcpThread(){
      //wait for messages
      while(1)
         if(messageFromNetwork)
            mMessageQueue.push(_message);
  }
  
  Network::udpThread(){
      //do some work
      while(1){
      if(mMessageQueue.size &gt; 0){
          message = mMessageQueue.front();
          mMessageQueue.pop();
          //process message
      }
    }
  }
  </code></pre>
  
  <p>Then I create a new network object and kick off threadTest in this example main function. Finally I wait in a loop for some kind of user intervention.</p>
  
  <pre><code>///////////////////
  int main(void){
      std::unique_ptr&lt;Network&gt; _network(new Network());
  
      unique_ptr-&gt;threadTest();
  
      while(1){
          //wait on user input or stop signal
      }
  
  }
  </code></pre>
  
  <p>So from my reading I think that as long as I don't exit main or if I did this in another function, as long as I don't let _network go out of scope, then mMessageMutex and mMessageQueue will be available for the two threads to use?</p>
  
  <p>I also just learned how to use unique_ptr (things have changed in c++ for an old timer!). So I'm hoping that when _network does go out of scope that mTCPthread, mUDPthread, and _network will all be destroyed and not leak.</p>
  
  <p>Thank you</p>