title: Thread End checking from another Thread
body: <p>I have a class which reads data from port through TcpClient. I've created 2 threads. </p>
  
  <ol>
  <li>Packet Reading Thread</li>
  <li>Packet Processing Thread</li>
  </ol>
  
  <p>1 Thread continuously reads bytes and once it gets a proper packet it adds that packet in a Queue and initiates the 2nd thread, which then reads packet from that Queue and processes it.</p>
  
  <p>The packet processing should be done sequentially. Therefore each time when the reading thread adds the packet in Queue, it checks that whether that Processing Thread is running or NOT. If NOT then it again starts that thread. This is because we don't want multiple packet processing threads running simultaneously.</p>
  
  <p>Now my question is actually related to that checking part. What I've done is that, I've added a simple bool variable in my class. And when I <strong>get into the packet processing thread</strong> I set that bool = true. While packet reading thread checks this bool variable, if it is true then it knows that the processing thread is running. And when packet processing thread reaches <strong>at end, it sets that bool = false.</strong></p>
  
  <p>Is this the correct way? Or is this approach prone to race condition?</p>
  
  <p>Thanks.</p>
  
  <p><strong>Update (a little detail):</strong></p>
  
  <pre><code>delegate void PacketProcessDelegate();
  PacketProcessDelegate PacketProcess = new PacketProcessDelegate(this.PacketProcessingThread);
  
  PacketReadingThread() {
      Packet = GetPacket();  // thread blocks until packet is NOT received
      Queue.Synchronized(this.Queue).Enque(Packet);
      if (!this.IsProcessing)
          this.PacketProcess.BeginInvoke(null, null);
  }
  
  PacketProcessingThread() {
      this.IsProcessing=true;
      while(true) {
          Queue syncQueue;
          syncQueueu = Queue.Synchronized(this.Queue);
          if(syncQueueu.Count &gt; 0)
              //packet extraction and processing code here
          else
              break;
      }
      this.IsProcessing=false;
  }
  </code></pre>
  
  <p><strong>Goals:</strong><br>
  Packet Processing thread either<br>
  *) should be terminated and should be restarted, but ThreadPool should be utilized in order to prevent creation of a new thread each time. Thats why I've used the BeginInvoke.<br>
  OR<br>
  *) it should be blocked somehow until another packet is NOT received.</p>