views:

64

answers:

1

Here is my problem: I have to be able to send and receive to a device over serial. This has to be done in a multi-threaded fashion. The flow is as follows:

  1. Wait for device to send me something - or if idle, then query status to see if online with device

  2. If device sends me something, then process message, acknowledge, and tell device to perform other commands as necessary

Right now, I have a receive thread and transmit thread. The receive thread has a while loop that keeps checking the serial port via ReadFile(...) for one byte. If I have a byte, then I begin building my buffer and then parse the data to determine what was sent to me.

The send thread takes the next command defined by the read thread and sends it via WriteFile to the same COM port. The key is that there is a receive/send relationship between myself and the device.

My question is, do I have a nested Producer/Consumer model here? If my receive thread is consuming from the device and the send thread is producing to the device, the threads need to inherently talk so they are synchronized-right? What is the best way to synchronize my efforts in efficiently and quickly talk to the device? Note: I am using C++ Builder 5 which has TThreads and can use critical sections and mutexes.

Edit: I am also using polling so I am open to using WaitCommEvent as well if this will work better!

+1  A: 

What resources are you sharing that you think you need to synchronize?

If you have something like a queue in between the two threads then that is a pretty classic producer/consumer model. E.G. If you just have one thread reading and then putting commands in a queue while another thread extracts from the queue, processes the command and writes to the device then you need to synchronize access to the queue with a mutex or semaphore.

Perhaps I'm missing something but this should only get complicated if you have multiple threads reading from the queue and the commands which need to be transmitted need to stay in order. So try to keep it simple.

Duck
Right, but how do I synchronize access to the device so that when I am reading, I am not writing? Global flag?
0A0D
Are you certain you have to do so? If so you can use a semaphore to sync the read/write operations. This http://stackoverflow.com/questions/1488712/is-it-safe-to-read-and-write-to-a-serial-port-at-the-same-time-via-different-thre might be helpful.
Duck