开发者

Producer/Consumer For Talking to Devices Serially

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 b开发者_JS百科y 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜