[英]Terminate threads in the PPL thread pool
Microsoft 的 PPL 庫包含強大的並行化概念,並使用線程池實現它們,因此在運行 PPL 任務時通常不會創建新線程。 但是,似乎沒有一種方法可以顯式停止線程池中的線程。
我想明確停止線程的原因是因為 Qt。 一些 Qt 方法將信息存儲在分配的類實例中,指向此類實例的指針存儲在線程本地存儲中。 只有在以優雅的方式停止線程時才會清除此內存。 如果沒有,Qt 無法清理這個分配的內存。
將 PPL 與 Qt 結合使用意味着該內存在退出時沒有適當地釋放,這本身不是問題,但不幸的是,我們的內存分配庫將這種未釋放的內存報告為內存泄漏(請參閱是否有人使用 valgrind 和 Qt?對於類似的問題)。
我們注意到,如果我們自己創建線程(因此不使用 PPL 線程池),則不會報告任何泄漏。 如果我們使用 PPL,則會報告泄漏。
所以,問題是:有沒有辦法顯式停止 PPL 線程池中的線程?
PPL 在 C++ 中遵循與 C# 中的異步編程非常相似的概念。
一般的想法是“合作取消” - 您可以要求一個線程停止,該線程決定何時可以取消。 你不應該殺死任務/線程,這樣線程就不會在未定義的指令處停止。
在這里您可以看到如何使用 ppl 停止線程/任務的示例:
include <ppltasks.h>
#include <concrt.h>
#include <iostream>
#include <sstream>
using namespace concurrency;
using namespace std;
bool do_work()
{
// Simulate work.
wcout << L"Performing work..." << endl;
wait(250);
return true;
}
int wmain()
{
cancellation_token_source cts;
auto token = cts.get_token(); // <-- allow early cancellation, therefore share a cancellation_token
wcout << L"Creating task..." << endl;
// Create a task that performs work until it is canceled.
auto t = create_task([&]
{
bool moreToDo = true;
while (moreToDo)
{
// Check for cancellation.
if (token.is_canceled()) //<-- check for cancellation in the background thread
{
// Cancel the current task.
cancel_current_task(); //<-- informs the caller, "hey I got it..."
}
else
{
// Perform work.
moreToDo = do_work();
}
}
}, token);
// Wait for one second and then cancel the task.
wait(1000);
wcout << L"Canceling task..." << endl;
cts.cancel();
// Wait for the task to cancel.
wcout << L"Waiting for task to complete..." << endl;
t.wait(); //<-- this is import
wcout << L"Done." << endl;
}
但是為了幫助您更多-您可以向我們提供一些源代碼嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.