有一个线程拥有它运行C ++的函子

Kel*_*tek 1 c++ multithreading stdthread c++17

如果要在c ++中的新线程中运行函子,则必须创建函子对象,然后将对它的引用传递给线程构造函数。这可以工作,但是将线程和函子对象作为单独的东西留给您。是否有可能拥有一个函子本身的线程,当在该线程上调用join时,该函子会被清除?可能的API之类的东西可能thread<FunctorType>(args, for, functor)会在线程类中创建functor对象,然后运行它。

bol*_*lov 7

当然是。该构造

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
Run Code Online (Sandbox Code Playgroud)

接受功能对象作为转发参考。这意味着如果您提供一个右值,它将移动函数。

例如

#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();
}
Run Code Online (Sandbox Code Playgroud)