LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Why does CmtDiscardThreadPool hang?

My call to CmtDiscardThreadPool hangs.  I read the following in the help.
 
"If your Thread Functions are not guaranteed to finish executing, you must make sure that no active threads exist in the pool before calling this function. Call CmtGetThreadPoolAttribute with the ATTR_TP_NUM_ACTIVE_THREADS attribute to determine the number of active threads in the pool. "
 
Can someone give me an example of how to make sure that there are no active threads in the pool?  Once I determine that there are active threads in the pool, how can I stop them so I can make the CmtDiscardthreadPool call?
Thanks,
Donna 
0 Kudos
Message 1 of 2
(3,056 Views)
As long as there are scheduled thread functions in a pool, CmtDiscardThreadPool waits for those functions to return before discarding the thread pool. Whenever you schedule a thread function, you must make sure that the function (thread) will return before you discard the thread pool (or exit the program). Typically, thread functions check for "quit" flags and return if the flag is set; the program sets this flag else where, like in a Quit callback. You can also wait for your thread functions to finish execution by calling the CmtWaitForThreadPoolFunctionCompletion function. The following is some simple code that uses a quit flag to signal a thread to exit.

#include <windows.h>
#include <utility.h>
#include <ansi_c.h>

static int quit = 0; /* Signals worker threads to return */

int CVICALLBACK ThreadFunction(void * data)
{
    while (!quit)
        Sleep(0);  
    return 0;
}

void main(void)
{
    int pool, numActiveThreads;
   
    CmtNewThreadPool(4, &pool);
    CmtScheduleThreadPoolFunction(pool, ThreadFunction, 0, 0);
    Sleep(100);
   
    quit = 1; /* Signal thread function to exit */
   
    /* Check for active threads before discarding the thread pool.    */
    /* This loop is really not required because CmtDiscardThreadPool */
    /* will anyway wait for all active thread functions to return.   */
    do
    {
        Sleep(0);
        CmtGetThreadPoolAttribute(pool,
            ATTR_TP_NUM_ACTIVE_THREADS, &numActiveThreads);
    } while (numActiveThreads > 0);
   
    CmtDiscardThreadPool(pool);
   
    puts("Hit enter to exit...");
    getchar();
}

0 Kudos
Message 2 of 2
(3,043 Views)