01-26-2018 05:12 PM
Is there no way to terminate a thread from the main thread?
If main thread schedules a thread from pool, can the main thread take action to terminate the second thread? The function CmtExitThreadPoolThread must be executed in the second thread as I understand it.
01-28-2018 04:52 AM - edited 01-28-2018 04:54 AM
The usual way to perform this task is to have a variable that determines the prosecution of the spawned thread or its termination. The variable, a global one, is set / reset in the main thread and read in the second thread which usually has a loop that has an exit condition tied to that variable.
This paradigm is shown for example in simple.prj example for multithreading: you can locate it either searching in the example finder (Help >> Find examples... menu function) with "thread" keyword or going directly to <cvisamplesfolder>\utility\threading\simple
01-31-2018 11:17 AM
Yes, that is how we're handling it now. The problem is we have to pepper the whole code in spawned thread with checks for the variable. I was hoping for a way out of that...
02-01-2018 03:34 AM
Instead of global variables, you can use windows signalling. Install a signal handle using RegisterWinMsgCallback() in each thread to handle the signals, and use PostMessage() to send signals to the threads.
02-01-2018 05:00 AM
An alternative to global variable could be calling PostDeferredCallToThread from the main thread to call a function executed in the spawned thread: that function could execute ExitThreadPoolThread to terminate the thread. The only caveat is that ExitThreadPoolThread terminates the function immediately: I don't know if it permits a correct termination of the thread function disposing of allocated resources and so on.
02-01-2018 05:33 AM
I modified simple.prj example to demonstrate how to use PostDeferredCallToThread and it shows that the thread is not properly terminated but rather killed immediately: this may not be good in some cases (probably most cases if not all). In modified example, Terminate (global) buttons properly close the thread manipulating the global variable, while Terminate (PostDfd) kills it with CmtExitThreadPoolThread.
I didn't mentioned this earlier, but for PostDeferredCallToThread to work, the thread must be processing events.
02-02-2018 06:24 PM
As far as I can tell, RegisterWinMsgCallback also requires code to process events.
I guess one must either puts calls for a global variable check or calls to process events all through the code in the spawned thread in order to exit the thread.