返回

C++如何在向量中插入JToG?

发布时间:2022-09-10 11:43:50 636
# golang

我正试着和新员工一起工作jthreads想把它们添加到std::vector这样我就可以轻松地一次阻止所有这些。

以下代码无法使用Visual Studio 2022编译:错误C2893:未能专门化函数模板的未知类型std::invoke(_Callable &&)noexcept()'

std::vector thread_handles;

thread_handles.emplace_back(std::make_shared
     (std::bind(&PrinterServer::RunInThread, 
                &printer_server, std::placeholders::_1)));

std::ranges::for_each(thread_handles.begin(), 
                     thread_handles.end(), 
                     [](std::jthread& thread_handle)
{
    thread_handle.request_stop();
});

std::ranges::for_each(thread_handles.begin(), 
                      thread_handles.end(), 
                      [](std::jthread& thread_handle)
{
    thread_handle.join();
});

下面是我使用单个jthread时生成的完整示例:

#include 
#include 
#include 
#include 
#include 

class PrinterServer
{
    std::string m_Name;
    bool m_Quit = false;

public:
    explicit PrinterServer(std::string name) : m_Name(std::move(name))
    {
    }

    void RunInThread(const std::stop_token interrupt)
    {
        using namespace std::chrono_literals;
        printf("\n%s> Started!\n", m_Name.c_str());

        // Register a interrupt callback  
        std::stop_callback cb(interrupt, [&]() { m_Quit = true; });

        // Main loop waiting to process requests until we are asked to stop
        while (!m_Quit)
        {
            // Do something...
            std::this_thread::sleep_for(500ms);
        }
        printf("\n%s> Terminate!\n", m_Name.c_str());
    }
};

int main()
{
    PrinterServer printer_server("MAIN PRINTER");

#if 1
    // OK I can request a single jthread to stop
    auto printer_server_thread_handle = std::jthread(printer_server);
    printer_server_thread_handle.request_stop();
    printer_server_thread_handle.join();
#else
    // On VS2022 14.30.30705
    // Error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&) noexcept()'

    std::vector thread_handles;
    // std::vector<std::make_shared> thread_handles;
    thread_handles.emplace_back(std::make_shared(std::bind(&PrinterServer::RunInThread, &printer_server, std::placeholders::_1)));
    std::ranges::for_each(thread_handles.begin(), thread_handles.end(), [](std::jthread& thread_handle)
    {
        thread_handle.request_stop();
    });
    std::ranges::for_each(thread_handles.begin(), thread_handles.end(), [](std::jthread& thread_handle)
    {
        thread_handle.join();
    });
#endif

    return 0;
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像