LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

How to start two threads at the same time

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;
}

 

 

0 Kudos
Message 1 of 2
(3,573 Views)

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.



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 2
(3,548 Views)