首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >终止PPL线程池中的线程

终止PPL线程池中的线程
EN

Stack Overflow用户
提问于 2019-02-01 03:17:05
回答 1查看 289关注 0票数 4

微软的PPL库包含强大的并行化概念,并使用线程池实现它们,因此在运行PPL任务时通常不会创建新的线程。但是,似乎没有一种方法可以显式地停止线程池中的线程。

我想显式停止线程的原因是因为Qt。一些Qt方法将信息存储在已分配的类实例中,指向此类实例的指针存储在线程本地存储中。只有当线程以适当的方式停止时,这个内存才会被清除。如果不是,Qt就不能清理这个已分配的内存。

结合使用PPL和Qt意味着这个内存在退出时没有被很好地释放,这本身不是一个问题,但是不幸的是这个未释放的内存被我们的内存分配库报告为一个内存泄漏(类似的问题请参阅Is anyone using valgrind and Qt? )。

我们注意到,如果我们自己创建线程(所以不使用PPL线程池),则不会报告任何泄漏。如果我们使用PPL,就会报告泄漏。

那么,问题是:有没有一种方法可以显式停止PPL线程池中的线程?

EN

回答 1

Stack Overflow用户

发布于 2020-07-06 05:02:02

类似于C#中的异步编程,PPL在C++中遵循非常相同的概念。

一般的想法是“协作取消”--你可以要求一个线程停止,这个线程决定何时可以取消。您不应该终止任务/线程,这样线程就不会在未定义的指令处停止。

这里你可以看到一个使用ppl停止线程/任务的示例:

代码语言:javascript
复制
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;
}

但是为了给你更多的帮助-你能给我们提供一些源代码吗?

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54467780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档