Multithreading 在不阻塞线程的情况下循环工作线程
您好,有没有一种方法可以运行一组线程(不阻塞它们)并在主线程发出信号时停止它们 例如,在此线程回调中:Multithreading 在不阻塞线程的情况下循环工作线程,multithreading,pthreads,threadpool,Multithreading,Pthreads,Threadpool,您好,有没有一种方法可以运行一组线程(不阻塞它们)并在主线程发出信号时停止它们 例如,在此线程回调中: void *threadCallback ( void * threadID) { syncPrint("Thread %lu started . Waiting for stop signal\n", threadID); pthread_mutex_lock(&stopSignalGuard); int i = 0; while(!stopSigna
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(…)阻止。是否可以运行此循环,直到主线程发出停止的信号?还是另一种方法
谢谢 如果线程在某些条件发生变化之前无法继续运行,则只需使用
pthread\u cond\u 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);
}