send TCP messages from two different threads
I have two threads that need to send TCP messages using the same already stablished connection. I have an object lets say tcpSe开发者_Python百科nder that I would like to use from booth threads. How can I design my software in order I would not have concurrency problems and lost messages?
Thanks!
You could model this as a producer/consumer where each thread injects messages into the TCPSender
whenever they are ready and the TCPSender
maintains a FIFO queue of messages. The insertions into the queue would be locked (within the TCPSender
) and processed in-order.
There would be another thread that is consuming the messages when the queue is not empty locking each time a message is removed from the queue.
Two immediate benefits are that you can support an arbitrary number of producers and the blocking is limited to inserting into a queue and not to actually sending the messages (from the point of view of the producer, that is).
You could create a Semaphore
which you acquire
before each send, and release
after each send. This would ensure that the resources is accessed by one thread at a time.
If you don't need to get an answer after sending this data, you can use a queue.
精彩评论