[英]How I can wait until a Win32 ThreadPool is finished with work, with external cancellation?
我正在嘗試在我的程序中使用 ThreadPool,但我有一個問題。
我需要有一個外部止損——過去,一個函數回調用於檢查外部止損,現在我必須這樣做。
在新的 ThreadPool API 中,我可以使用CloseThreadpoolCleanupGroupMembers()
並等待所有排隊的作業,或取消掛起的作業並等待執行。 但是如果我調用CloseThreadpoolCleanupGroupMembers()
並等待所有,我不能對外部事件做一些事情。
在不調用 this 或類似的阻塞函數的情況下等待所有作業的好方法是什么?
我想,我可以用一個工作計數器來做到這一點 - 完成並排隊,但也許還有另一個好的解決方案?
在這種情況下,我會將“線程計算完成”和“外部事件”消息推送到單個線程安全隊列中。 然后主線程可以連續循環遍歷隊列並處理隊列中的事件。
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
。 在這種情況下,您可以在外部停止時清理任務列表並使用另一個取消功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.