Search code examples
multithreadingpthreadsthreadpool

Looping an workers threads without blocking them


Hello is there a way to run a set of threads (without blocking them )and stop when they are signaled by the master thread ?

For example in this thread callback :

void *threadCallback ( void * threadID) {
    syncPrint("Thread %lu started . Waiting for stop signal\n", threadID);
    pthread_mutex_lock(&stopSignalGuard);
    int i = 0;
    while(!stopSignal) {
        i++;
        syncPrint("increment : %d \n",i);
        pthread_cond_wait(&stopCondition,&stopSignalGuard);
    }
    syncPrint("Stop signal received. Thread %lu will terminate...\n",(long)threadID);
    pthread_mutex_unlock(&stopSignalGuard);
    pthread_exit(NULL);
}

From what I see, the while loop does not effectively run. The execution is blocked by pthread_cond_wait(...). It is possible to run this loop until the main thread signals the workers to stop ? Or is the another way to do this ?

Thanks !


Solution

  • You only need to use pthread_cond_wait() if the thread cannot make progress until some condition has changed.

    In your case, the thread apparently has other things it can do, so you just check the flag within a mutex-protected section then continue on:

    int getStopSignal(void)
    {
        int stop;
    
        pthread_mutex_lock(&stopSignalGuard);
        stop = stopSignal;
        pthread_mutex_unlock(&stopSignalGuard);
    
        return stop;
    }       
    
    void *threadCallback (void * threadID)
    {
        int i = 0;
    
        syncPrint("Thread %lu started . Waiting for stop signal\n", threadID);
    
        while(!getStopSignal()) {
            i++;
            syncPrint("increment : %d \n",i);
        }
    
        syncPrint("Stop signal received. Thread %lu will terminate...\n",(long)threadID);
        pthread_exit(NULL);
    }