是否可以使用 boost::asio 通过线程 ID 将函数排队到特定线程?

Is it possible to queue a function to a specific thread by its thread id using boost::asio?

我正在尝试通过线程 ID 在特定线程上对一个简单函数进行排队。
我不需要停止线程,只需要 post 它的一个函数。该功能只需要在特定时间范围内执行。
我一直在考虑使用 asio::post 发送函数,但不确定如何找到和绑定线程。
有什么办法吗?或者通过保存线程的本机处理程序来实现它会更可行吗? (我认为我可以做到)


我是多线程和 boost::asio 的新手,所以任何帮助都将非常有用。
提前致谢!

为什么要使用 ID 将任务分配给特定线程?你让 asio 为你做那件事。
例如,你可以通过调用 asio::io_context::run 让线程在某个时刻等待。然后,当您将 post 任务时,将从那些等待的线程中随机选择一个空闲线程,它将执行 posted 任务。例如:

asio::io_context context;
asio::executor_work_guard guard(context.get_executor()); // used to manage the task status

auto workerThread = [&](){
     context.run(); // threads will block here, waiting for tasks to be posted and then execute them concurrently
};

auto foo = [](auto && value){
     // obtain mutex here
     std::cout << value << '\n';
     // release mutex 
};

auto threadA = std::thread(workerThread);
auto threadB = std::thread(workerThread);

// assign the tasks
context.post(std::bind(foo,1));
context.post(std::bind(foo,2));

guard.reset(); // inform the threads there is no more work to do
threadA.join();
threadB.join();