[Solved] C/C++ code using pthreads to execute sync and async communications


There is no general problem with two threads executing system calls on the same socket. You may encounter some specific issues, though:

  • If you call recvfrom() in both threads (one waiting for the PLC to send a request, and the other waiting for the PLC to respond to a command from the server), you don’t know which one will receive the response. To get around this, you can dedicate one thread to reading from the PLC, and have it pass reply messages from the PLC to the sending thread using shared queue or similar structure.

  • You have to be careful when you close a socket that could be in use by another thread – because of the way file descriptors are reused, it’s easy to have a race condition that ends up with a thread acting on the wrong socket.

1

solved C/C++ code using pthreads to execute sync and async communications