Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good Coding? (Multiple Message Loops)

I'm in need of some advice in proper coding:

I'm working on a program where multiple serial connections are used. Each communication line has a controller working as an abstraction layer. Between the controller and the serial port, a protocol is inserted to wrap the data in packages, ready for transfer. The protocol takes care of failed deliveries, resending etc. To ensure that the GUI won't hang, the each connection line (protocol and serial port) is created on a separate thread. The controller is handled by the main thread, since it has controls in the GUI.

Currently, when I create the threads, I have chosen to create a message loop on them (Application.Run()), so instead polling buffers and yielding if no work, i simply invoke the thread (BeginInvoke) and uses the message loop as a buffer. This currently works nicely, and no serious problems so far.

My question is now: Is this "good coding", or should i use a while loop on the tread and be polling buffers instead?, or some third thing?

I would like to show code, but so far it is several thousand lines of code, so please be specific if you need to see any part of the code. :)

Thank you.

like image 955
Anders Avatar asked Jul 25 '12 06:07

Anders


2 Answers

Using message loops in each thread is perfectly fine; Windows is optimized for this scenario. You are right to avoid polling, but you may want to look into other event-based designs that are more efficient still, for example preparing a package for transfer and calling SetEvent to notify a thread it's ready, or semaphore and thread-safe queue as Martin James suggests.

like image 54
tenfour Avatar answered Sep 23 '22 21:09

tenfour


I'm not 100% sure what you are doing here but, with a bit of 'filling in' it doesn't sound bad:)

When your app is idle, (no comms), is CPU use 0%?

Is your app free of sleep(0)/sleep(1), or similar, polling loops?

Does it operate with a reasonably low latency?

If the answers are three 'YES', you should be fine :)

There are a few, (very few!), cases where polling for results etc. is a good idea, (eg. when the frequency of events in the threads is so high that signaling every progress event to the GUI would overwhelm it), but mostly, it's just poor design.

like image 42
Martin James Avatar answered Sep 24 '22 21:09

Martin James