LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Multithreading and ProcessSystemEvent()

Hi. I'm developing a generic - configurable communication DLL which I will use in my future applications. To obtain a great flexibility I used three threads, one thread for each level of my protocol. The data exchange is done with thread safe queues.
During debug phase I found a strange problem: sometimes a thread didn't receive any data from the queue and timed out. You can imagine this flow:
 
1. Thread A writes a packet to 'QueueAtoB'
2. Thread A waits (polling) data from 'QueueBtoA': while ((!ItemsInQueue) && (!TimeOut));
 
In the meantime thread B is always polling for data in 'QueueAtoB'.
 
I saw that, after Thread A writes data to Queue, Thread B doesn't work. It seems Thread A obtain a bigger priority and Thread B doesn't live for some seconds...
 
I solved this problem putting a ProcessSystemEvent() inside the polling of point 2 above: while ((!ItemsInQueue) && (!TimeOut)) ProcessSystemEvent();
 
My question: Is this correct ??
 
Thank you very much.
0 Kudos
Message 1 of 2
(3,062 Views)

I've noticed this problem as well. Windows appears to have a feature that if you have more than one 'busy' thread of the same priority, one of the threads runs all the time and the others get no processor time at all.

Rather than using ProcessSystemEvents(), which might have undesirable side effects, I'd suggest you use a call to the Windows API function Sleep(), with a non-zero time (e.g. Sleep(5)). This will suspend the thread to allow the other thread to run without causing anything else to happen. Note that you should use Sleep() rather than the CVI function Delay(), which is a 'busy' wait (it does not suspend the thread).

--
Martin
Certified CVI Developer
0 Kudos
Message 2 of 2
(3,058 Views)