Hello是否有办法运行一组线程(不阻塞它们)并在主线程发出信号时停止?
例如在此线程回调中:
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(...)阻止。可以运行此循环,直到主线程指示工人停止?或者是另一种方法吗?
谢谢!
答案 0 :(得分:0)
如果线程在某些条件发生变化之前无法取得进展,则只需使用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);
}