I have two threads that need to send TCP messages using the same already stablished connection. I have an object lets say tcpSender 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
TCPSenderwhenever they are ready and theTCPSendermaintains a FIFO queue of messages. The insertions into the queue would be locked (within theTCPSender) 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).