gpt4 book ai didi

c++ - 将对虚类实现的引用作为线程参数传递

转载 作者:行者123 更新时间:2023-11-28 06:32:49 24 4
gpt4 key购买 nike

我再次需要您的帮助,使 std::thread 与模板对象一起工作。这次我的问题是在其中一个论点中。

我尝试将对虚拟类的(有效)实例化的引用作为我的线程的参数之一传递,但它不起作用。请注意,传递指针而不是引用可以解决所有问题。但是,为什么我不能给出引用(我更喜欢,原因有很多)

重现我的错误的小代码:

#include <cstdio>
#include <thread>
#include <vector>

template<typename T>
class functor { public: virtual T operator()(T) const = 0; };

template<typename T>
class square : public functor<T>
{
public:
T operator()(T f) const { return f*f; }
};

template<typename T>
void thread(const functor<T>& func, size_t imin, size_t imax) // line1
{
for(size_t i=imin; i<imax; ++i)
{
T arg = T(i);
std::cout << arg << "=>" << (func)(arg)) << std::endl; // line2
}
}

template<typename T>
void threadlauncher(const functor<T>& func, size_t imin, size_t imax, size_t nbthread)
{
size_t window = (imax-imin)/nbthread + ((imax-imin)%nbthread?1:0);
std::vector<std::thread> threads;
for (size_t idthread=0; idthread<nbthread; ++idthread)
{
size_t tmin = std::min(window*(idthread+0), imax);
size_t tmax = std::min(window*(idthread+1), imax);
threads.push_back(
std::thread(&thread<T>, func, tmin, tmax) // line3
);
}
for (std::thread& thread : threads)
thread.join();
}
int main()
{
square<float> func;
threadlauncher<float>(func, 0, 10, 3);
return 0;
}

编译器 (gcc 4.9.2) 告诉我我的对象无效,因为 operator()threadlauncher 中是虚拟的

请注意,更改代码以使用指针传递线程的参数可以解决此问题

void thread(const functor<T>* func, size_t imin, size_t imax) // line1
std::cout << arg << "=>" << (*func)(arg)) << std::endl; // line2
std::thread(&thread<T>, &func, tmin, tmax) // line3

我怎样才能让他明白我的推荐是有效的?

编辑

我从编译器收到一条长长的/不可读的错误消息。我想重要的部分是

src/functorthreads.cc:50:38:   required from here
/usr/include/c++/4.9.2/functional:1713:9: erreur: invalid abstract parameter type ‘functor<float>’
__type;
^
src/functorthreads.cc:6:7: note: because the following virtual functions are pure within ‘functor<float>’:
class functor
^
src/functorthreads.cc:9:13: note: T functor<T>::operator()(T) const [with T = float]
virtual T operator()(T) const = 0;

最佳答案

std::thread 获取其参数的拷贝。函数的参数是一个引用并不重要.... thread 构造函数仍将复制参数,因为它们被传递给另一个线程。这就是指针起作用的原因,因为它们正在被复制。

如果您知道您的对象将在线程的整个生命周期内保持在范围内,您可以使用 std::ref 来包装您的参数:

std::thread(&thread<T>, std::ref(func), tmin, tmax)

关于c++ - 将对虚类实现的引用作为线程参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27231741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com