如何等待Win32线程池完成工作并进行外部取消
How I can wait until a Win32 ThreadPool is finished with work, with external cancellation?
我试图在程序中使用ThreadPool,但我有一个问题。
我需要一个外部停止——过去,函数回调用于检查外部停止,现在我也必须这样做。
在新的ThreadPool API中,我可以使用CloseThreadpoolCleanupGroupMembers()
并等待所有排队的作业,或者取消挂起的作业并等待执行。但是,如果我调用CloseThreadpoolCleanupGroupMembers()
并等待所有事件,我就无法对外部事件执行某些操作。
在不调用这个或类似的阻塞函数的情况下,等待所有作业的好方法是什么?
我想,我可以用一个作业计数器来完成和排队,但也许还有另一个好的解决方案?
在这种情况下;线程计算完成";以及";外部事件";消息转移到单线程安全队列中。然后,主线程可以连续地循环通过队列并处理它之外的事件
enum EventType {
THREAD_CALCULATION_FINISHED,
EXTERNAL_EVENT
};
// you could probably use an atomic-op ring buffer instead
std::queue<EventType> message_queue;
std::mutex message_queue_mutex;
// ...
void wait_on_thread_pool() {
bool stopped = false;
int thread_counter = NUM_THREADS;
while (!stopped) {
message_queue_mutex.lock();
while (!message_queue.empty()) {
EventType e_type = message_queue.front();
message_queue.pop();
switch (e_type) {
case THREAD_CALCULATION_FINISHED:
--thread_counter;
if (thread_counter == 0) {
stopped = true;
}
break;
case EXTERNAL_EVENT:
stopped = true;
break;
}
}
message_queue_mutex.unlock();
}
}
我找到了一个很好的解决方案:将线程保存列表与任务一起使用,并在列表中添加的每个元素中使用SubmitThreadpoolJob
。在这种情况下,您可以在外部停止时清除任务列表,并使用另一个取消功能。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 挂起和取消挂起一个文件DLL
- 导入库可以跨dll版本工作吗
- 如何取消对nullptr的屏蔽,返回正确的对象
- C++取消引用指针.为什么会发生变化
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- C++:检查动态取消分配是否正常工作
- 为什么 openMP 取消构造不取消工作共享区域
- 提升::接受者::取消未按预期工作
- 迭代器不是可取消引用的堆栈(表达式树)和循环无法正常工作