【问题标题】:Running a function on the main thread from a boost thread and passing parameters to that function从 boost 线程在主线程上运行一个函数并将参数传递给该函数
【发布时间】:2012-11-20 18:32:15
【问题描述】:

我有一些代码在 boost 线程中运行,它修改了由主线程处理的东西,这些东西不起作用,这是有道理的。

在 android 上,我将拥有 Handler,它是一个消息队列,它将在主线程上执行我的代码,我可以将任何我想要的参数传递给这个处理程序。

我想对 boost 做同样的事情

所以在我的主线程上,我执行以下操作:

boost::thread workerThread(boost::bind(&SomeClass::pollService, this));

我的 pollService 方法:

SomeClass::pollService()
{
     //get some stuff from a web service
     //parse the json response
     //NEEDED part: call a function to be executed on the main thread and hand it some functions
}

附:我看过很多 io_service.post 的例子,但我仍然不知道该怎么做,而且我读了一个回答说要使用 asio strand 但我也无法理解。

有人可以帮我把它笨一点吗? 请不要写太抽象的东西,我不会理解,我没有这方面的经验。 谢谢

【问题讨论】:

    标签: boost boost-asio boost-thread boost-bind


    【解决方案1】:

    是的,io_service::post() 是一种方便的工具,可以将函子从一个线程发送到另一个线程,但目标线程应该执行 io_service::run(),这是一个阻塞函数(类似于 io_service“消息循环”)。因此,假设您的主线程如下所示:

    int main()
    {
      // do some preparations, launch other threads...
      // ...
      io_service io;
      io.run();
    }
    

    ...假设您可以从运行在另一个线程中的pollService 访问io 对象,您可以执行以下操作:

    SomeClass::pollService()
    {
      // do something...
      // ...
      io.post([=] { doStuffThatShoudRunInMainThread(); });
    }
    

    如果您的编译器不支持 c++11 lambda,请使用 bind -- 但请注意 post 需要空函子,即不接受参数的函数对象。

    【讨论】:

    • 那么如何将参数传递给我的函数?
    • 请注意,我已经解决了我的问题,方法是创建一个 std:queue 并将东西放入其中,而 while(!queue.empty()) 我在 gui 线程中做一些事情,该线程已经循环每个滴答声,并且工作正常,我需要知道才能知道将来如何正确地做到这一点
    • @Shereef 如果您使用 lambda 语法 - 将参数直接传递给 doStuffThatShoudRunInMainThread(),否则在创建仿函数时绑定参数:bind(&doStuffThatShoudRunInMainThread, arg1, arg2, arg3)。当然,如果它是一个成员函数,你应该将它绑定到this,或者更好地使用shared_from_this
    • 你能看一下stackoverflow.com/q/13785640/435706吗,谢谢
    • void funtionToCreateThread() { //code to update ui //create thread //thread join} 这里 thread join 代码块在开始时更新 ui 调用,如何解决这个问题?由于 ioserver run 也是一个阻塞调用,我觉得第一个注释代码不起作用。你能建议如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多