C ++ pthread:如何在pthread_create中将io_service.run()设置为参数

c++ pthread: how to set io_service.run() as parameter in pthread_create?

本文关键字:pthread service run 设置 参数 io create 中将      更新时间:2023-10-16

我想在 pthread 中运行一个回调函数。

我目前停留在以下代码中:

//maintest.cpp
....
main{
...
//setting up the callback function SimT:
boost::asio::io_service io;
boost::asio::deadline_timer t(io);
SimT d(t);
//calling io.run() in another thread with io.run()
pthread_t a;
pthread_create( &a, NULL, io.run(),NULL); ----->Here I dont know how to pass the io.run() function
...
//other stuff that will be executed during io.run()
}

我应该如何在pthread_create参数中指定io.run()?谢谢

您需要传递指向非成员函数的指针,例如:

extern "C" void* run(void* io) {
    static_cast<io_service*>(io)->run();
    return nullptr; // TODO report errors
}
pthread_create(&a, nullptr, run, &io);

当然,现在没有必要使用本机线程库:

std::thread thread([&]{io.run();});

您可能希望创建一个函子对象并将其传入。有关更多信息,请检查:C++函子 - 及其用途

编辑:如果您使用的是C++11,则此解决方案将更加干净:将Lambda传递给pthread_create?