如果要在c ++中的新线程中运行函子,则必须创建函子对象,然后将对它的引用传递给线程构造函数。这可以工作,但是将线程和函子对象作为单独的东西留给您。是否有可能拥有一个函子本身的线程,当在该线程上调用join时,该函子会被清除?可能的API可能是类似于thread<FunctorType>(args, for, functor)
的API,它将在线程类中创建functor对象,然后运行它。
是的,当然。 constructor
template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );
接受功能对象作为转发参考。这意味着如果您提供一个右值,它将移动函数。
例如
#include <thread>
#include <iostream>
struct F
{
auto operator()() { std::cout << "Hello World" << std::endl; }
};
auto test()
{
std::thread t1{[]{ std::cout << "Hello World" << std::endl; }};
std::thread t2{F{}};
t1.join();
t2.join();
}