从升压线程运行在主线程函数,参数传递到该功能 [英] Running a function on the main thread from a boost thread and passing parameters to that function
问题描述
我在修改的东西由不正常的主线程处理的线程提升一些code运行,这是有道理的。
I have some code running in a boost thread that modifies stuff handled by the main thread which is not working and it makes sense.
在Android上我将有处理程序
这是将执行在主线程我的code消息队列,我可以通过我想这一切参数处理程序。
On android i would have the Handler
which is a message queue that would execute my code on the main thread and i can pass whatever parameters i want to this handler.
我想要做同样的升压
等我的主线程我做到以下几点:
so on my main thread i do the following:
boost::thread workerThread(boost::bind(&SomeClass::pollService, this));
我pollService方式:
My pollService method:
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
}
P.S。我看过许多 io_service.post
的例子,我仍然不知道如何做到这一点的,也是我读答案说要用 ASIO
链
但我也无法理解它。
P.S. I have looked at many io_service.post
examples and i still have no clue how to do it, and also i read an answer that said to use asio
strand
but i am also unable to understand it.
有人能请哑下来我吗?
请不要写的东西非常抽象,我不会明白,我不是这个经验。
谢谢
Can some one please dumb it down for me ? Please don't write something so abstract that i won't understand, I am not experienced in this. Thank you
推荐答案
是 io_service对象::后()
是一个方便的工具来从一个线程张贴到仿函数另一个,但目标线程应该执行 io_service对象::运行()
,这是阻止功能(这是一种 io_service对象
的消息循环)。因此,假设你的主线程看起来是这样的:
Yes, io_service::post()
is a convenient facility to post a functor from one thread to another, but the destination thread should execute io_service::run()
, which is blocking function (it's kind of io_service
"message loop"). So, assuming your main thread looks like this:
int main()
{
// do some preparations, launch other threads...
// ...
io_service io;
io.run();
}
...假设你有从 pollService
到 IO
对象的访问在另一个线程运行,你可以做到以下几点:
...and assuming you've got an access to io
object from pollService
running in another thread, you can do the following:
SomeClass::pollService()
{
// do something...
// ...
io.post([=] { doStuffThatShoudRunInMainThread(); });
}
如果你的编译器不支持C ++ 11 lambda表达式,使用绑定
- 但是请注意,后
预计无元仿函数,即函数对象,不接受参数。
If your compiler doesn't support c++11 lambdas, use bind
-- but note that post
expects nullary functor, i.e. a function-object that doesn't accept parameters.
这篇关于从升压线程运行在主线程函数,参数传递到该功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!