循环工作线程而不阻塞它们
Looping an workers threads without blocking them
你好,有没有办法 运行 一组线程(不阻塞它们)并在主线程发出信号时停止?
例如在这个线程回调中:
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_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);
}
你好,有没有办法 运行 一组线程(不阻塞它们)并在主线程发出信号时停止?
例如在这个线程回调中:
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_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);
}