【问题标题】:Looping an workers threads without blocking them循环工作线程而不阻塞它们
【发布时间】:2018-10-27 18:24:18
【问题描述】:

你好,有没有办法运行一组线程(不阻塞它们)并在主线程发出信号时停止?

例如在这个线程回调中:

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

据我所知,while 循环没有有效运行。执行被 pthread_cond_wait(...) 阻塞。是否可以运行此循环,直到主线程向工作人员发出停止信号?或者是另一种方式来做到这一点?

谢谢!

【问题讨论】:

    标签: multithreading pthreads threadpool


    【解决方案1】:

    如果线程在某些条件改变之前无法继续前进,您只需要使用pthread_cond_wait()

    在您的情况下,线程显然还有其他可以做的事情,因此您只需检查受互斥体保护的部分中的标志,然后继续:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      相关资源
      最近更新 更多