微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法将一些 unique_ptr 的右值引用传递给线程池

如何解决有没有办法将一些 unique_ptr 的右值引用传递给线程池

我使用的是 C++11(我不能使用更新的 C++ 标准)。 我无法将带有 unique_ptr 右值引用的函数传递给我的线程池。

这是一个简单的代码

使用 test2 函数而不使用 test1

#include "thread-pool.hpp"
#include <iostream>
#include <string>

struct Mystruct
{
    int a;
    int b;
    std::string c;
};

void test1(int id,std::unique_ptr<Mystruct>&& ms,int a)
{
    while (true)
    {
        std::cout << ms->c << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(a));
    }
}

void test2(int id,std::string&& c,int a)
{
    while (true)
    {
        std::cout << c << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(a));
    }
}

int main()
{
    ctpl::thread_pool p(10);
    Mystruct* ms = new Mystruct;
    std::unique_ptr<Mystruct> msp(ms);
    p.push(test1,msp,10);
    p.push(test2,"this is the end","hello from the other side",5);
    return 0;
}

我收到这些错误

no instance of overloaded function "ctpl::thread_pool::push" matches the argument list
C2893   Failed to specialize function template 'std::future<unkNown-type> ctpl::thread_pool::push(F &&,Rest &&...)'
C2780   'std::future<unkNown-type> ctpl::thread_pool::push(F &&)': expects 1 arguments - 3 provided
C2672   'ctpl::thread_pool::push': no matching overloaded function found

我将 vit vit repository 用于我的线程池实现。我正在将此链接用于 thread-pool.hpp 文件thread pool 实现。

我无法更改 test1函数参数,因为我正在使用其他 API。 有没有办法将此函数传递给我的线程池对象或线程池的另一个实现。

解决方法

有没有办法将一些 unique_ptr 的右值引用传递给线程池

你不应该这样做。传递右值引用表明该函数取得了指针的所有权;在函数签名中发出“获取所有权”信号的正确方法是按值获取参数:

:- dynamic([yes/1,no/1]).

并在客户端代码中使用 std::move 来传递参数:

void test1(int id,std::unique_ptr<Mystruct> ms,int a) // << receive ms by value
{
    // ...
}

或:

std::unique_ptr<Mystruct> msp(ms);
p.push(test1,std::move(msp),10);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。