首页 > 解决方案 > 在多线程应用程序中使用智能指针

问题描述

我需要执行一些计算,这取决于两个或多个步骤,如下所示:

class A
{
public:
    double step1() { return 2.5; }
};

class B
{
public:
    double step2() { return 1.2; }
};

class Result
{
public:
    Result(std::shared_ptr<A> _a, std::shared_ptr<B> _b) : a(_a), b(_b) {};

    double getResult() { return a->step1() + b->step2(); }

private:
    std::shared_ptr<A> a;
    std::shared_ptr<B> b;
};

实际上,第 1 步和第 2 步需要多态行为,因此这些(共享)指针将指向“接口”类,但这里的细节并不重要。

现在,最后的计算getResult()也需要多态行为,所以我创建了一个(唯一)指针Result,创建了一个 lambda 调用getResult(),并将该 lambda 传递给我的线程,如下所示:

void run_multi_threaded_calculation()
{
    auto result = create_result_unique_ptr();

    const int nThreads = 4;
    std::vector<double> save(nThreads);

    auto task = [&](int n) {
        // Preprocessing before getResult()
        save[n] = n * result->getResult();
    };

    std::vector<std::thread> threads;
    threads.reserve(nThreads);
    for (size_t i = 0; i < nThreads; ++i)
    {
        threads.push_back(std::thread(task, i));
    }

    for (auto& th : threads)
        th.join();

    for (const auto& s : save)
        std::cout << s << '\n';
}

问题 1:我是否使用了智能指针和 lambda 捕获的正确配置,例如unique_ptrtoResultshared_ptrtoAB?经过一些猜测并检查更改智能指针类型后,上述编译(但不编译 ifabin Resultare unique_ptr),但我不确定这是否是解决此问题的最佳方法。

问题 2:如果我用等效的(或者我认为的)函数对象替换 lambda,那么我的代码不会编译(错误 C2661: 'std::tuple<ResultFunctor,unsigned int>::tuple': no 重载函数需要2 个论点)。智能指针是否缺少某些东西,或者线程的工作方式,或者我的函数对象定义可能存在一些问题?

以下是相关更改:

class ResultFunctor
{
public:
    ResultFunctor(std::unique_ptr<Result> _result, std::vector<double>& _save) : result(std::move(_result)), save(_save) {};

    void operator() (int n) { save[n] = n * result->getResult(); }

private:
    std::unique_ptr<Result> result;
    std::vector<double>& save;
};

并替换以下行:

void run_multi_threaded_calculation()
{
    // Other stuff is unchaged...

    /*auto task = [&](int n) {
        // Preprocessing before getResult()
        save[n] = n * result->getResult();
    };*/

    auto task = ResultFunctor(std::move(result), save);

    // other stuff is unchanged...
}

标签: c++multithreadinglambdasmart-pointersfunction-object

解决方案


您遇到的部分问题是您正在unique_ptr四处走动。但是move,当您尝试将 ResultFunctor 类中的那个传递给 std::thread 时,您错过了一个:

threads.push_back(std::thread(task, i));

如果您必须使用 unique_ptr,那么您很可能需要在 ResultFunctor 中使用 move c'tor:

class ResultFunctor
{
public:
    ResultFunctor(std::unique_ptr<Result> _result, std::vector<double>& _save) : result(std::move(_result)), save(_save) {};

    void operator() (int n) { save[n] = n * result->getResult(); }

    // Move c'tor rough un-tested example
    ResultFunctor(ResultFunctor&& rf) :
        result(std::move(rf.result)),
        save(rf.save)
    {};

private:
    std::unique_ptr<Result> result;
    std::vector<double>& save;
};

这样您就可以将其移动到 std::thread 的 c'tor 中,该 c'tor 采用 r 值 ref

threads.push_back(std::thread(std::move(task), i));

至少这是我能看到的主要问题,即使它不会导致您当前的错误。

注意:您的 lambda 与您的“等效”仿函数类完全不同。您的 lambda 是通过引用捕获的。然而,当你将它传递给线程时,这并不是真的那么安全,REAL unique_ptr 可能会超出范围并破坏它!

所以这不是一个很好的解决方案。在 c++14 中,我相信您可以使用 move 捕获 unique_ptr:如何将 unique_ptr 捕获到 lambda 表达式中?https://isocpp.org/wiki/faq/cpp14-language#lambda-captures


推荐阅读