I have a class which reads data from port through TcpClient. I’ve created 2 threads.
- Packet Reading Thread
- Packet Processing Thread
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.
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.
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 get into the packet processing thread 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 at end, it sets that bool = false.
Is this the correct way? Or is this approach prone to race condition?
Thanks.
Update (a little detail):
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 > 0)
//packet extraction and processing code here
else
break;
}
this.IsProcessing=false;
}
Goals:
Packet Processing thread either
*) 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.
OR
*) it should be blocked somehow until another packet is NOT received.
You’ve definitely got a race condition, without any more locking than has been described. If two packets come in in quick succession, you may see that the flag is false twice and start two different threads. You could avoid this by making the reading thread set the flag to false when it’s starting the thread – so the flag means “a thread is running or starting”.
It’s not clear why you need to keep starting threads anyway – why not just have one processing thread which blocks waiting for new packets when the queue is empty? If you’re using .NET 4 this is made really easy using
BlockingCollection<T>.EDIT: If you don’t need the packets to be processed in a particular order, you could just start a new thread pool work item for each packet: