C ++ pthread:如何在pthread_create中将io_service.run()设置为参数
c++ pthread: how to set io_service.run() as parameter in pthread_create?
我想在 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?
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 直接读取 pthread 互斥锁的所有者字段是否安全?
- Windows Service 可以枚举桌面顶级窗口吗?
- 为什么 pthread 会减慢代码速度?
- 对 pthread CLion 的未定义引用
- bad_weak_ptr使用从 boost::asio::io_context::service 继承的类
- C++ API-MS-WIN-SERVICE-PRIVATE-L1-1-1.DLL依赖项问题
- C++ 17:pthread的生成文件标志