11-02-2013 04:48 PM - edited 11-02-2013 04:49 PM
Hi there,
I want to include multithreading in the CVI program. I have two tasks which has no dependence between them, so I would like to start two threads for perform the tasks. I follow the introduction http://www.ni.com/white-paper/3663/en/ to start my code. In my code, I add a command button, when it is pressed, I create two threads to perform the tasks. In each task, I have a big loop and in each iteration, I use ProcessSystemEvents to avoid no response on system message. But it doesn't work actually, the program suspended. I wonder must I initialize the threads in main. I am looking for a way to start the threads in the callback function for a button since I am not starting those threads at the beginning but while it is triggered.
the main frame of the code looks
int CVICALLBACK Test1(void *functionData) { int i=0; for (i = 0; i<100000; i++) {ProcessSystemEvents();} return 0; } int CVICALLBACK Test2(void *functionData) { int i = 0; for (i = 0; i<100000; i++) {ProcessSystemEvents();} return 0; } int CVICALLBACK cmdcb(int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { int threadID1, threadID2; if (event==EVENT_COMMIT) { SetPanelAttribute(panelHandle, ATTR_DIMMED, 1); CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test1, NULL, &threadID1); CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test2, NULL, &threadID2); CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID1, 0); CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID2, 0); } return 0; }
11-03-2013 04:09 PM
In my opinion your threads may be simply lasting longer than expected due to an incorrect sleep policy of threads paired with with ProcessSystemEvents () in the loop.
I made up a quick example that shows this behaviour: playing with "Do not sleep" and "Call ProcessSystemEvents" options you can see how threads execute.
BTW: do not forget to release the thread function IDs at the end of functions.