c++ pthread : how to set io_service. run() 作为 pthread_create 中的参数?

标签 c++ multithreading boost callback pthreads

我想在 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++ pthread : how to set io_service. run() 作为 pthread_create 中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814728/

相关文章:

multithreading - 线程中的临界区是什么?

java - 使 Java Tic Tac Toe 服务器多线程化

c++ - 如何从源代码安装 boost 获得与从存储库安装 boost 相同的结果?

c++ - 为什么 clang 会混淆 Boost 和 STL?

c++ - Boost单元测试可以多线程吗?

c++ - 如何将 'const boost::filesystem2::path' 变成 'const char *' ?

c++ - 在数组中存储结构 (C++)

java - 如何分别维护每个线程的状态

c++ - OpenCV 错误:断言失败 <scn == 3::scn == 4> 在未知函数中,

c++ - 引用类型的 std::optional 特化