简体   繁体   English

pthreads:在主线程上执行 function

[英]pthreads: perform function on main thread

I'm looking for the analogous of Cocoa's我正在寻找可可的类似物

-[NSObject performSelectorOnMainThread: withObject: waitUntilDone:]

method.方法。

So basically I have a function that does some work on a separate thread but it must perform some synchronous calls that need to be performed on the main one.所以基本上我有一个 function 在一个单独的线程上做一些工作,但它必须执行一些需要在主线程上执行的同步调用。

in cocoa, the message is added to the run loop, which is cleared as part of its iteration.在 cocoa 中,消息被添加到运行循环中,作为其迭代的一部分被清除。

to simulate this:模拟这个:

  • you'll a want a run loop你会想要一个运行循环
  • an abstract message system一个抽象的消息系统
  • and a reference counting mechanism (in most cases)和引用计数机制(在大多数情况下)
  • a way to add those messages to a run loop for scheduled execution一种将这些消息添加到运行循环以进行计划执行的方法

timers would be a nice addition计时器将是一个不错的补充

to accomplish something similar using pthread interfaces exclusively, start by reading up on conditions pthread_cond_t .要专门使用 pthread 接口完成类似的事情,首先要阅读条件pthread_cond_t

i know of no pthread interface with a 1-1 relationship for what you're trying to accomplish.我知道您要完成的工作没有具有 1-1 关系的 pthread 接口。 conditions also operate without run loops, so you may need to bring that to the table, if you do not reuse a run loop implementation.条件也可以在没有运行循环的情况下运行,因此如果您不重用运行循环实现,您可能需要将其带到桌面上。 if you use run loops, then you just need a lock to add messages to a thread with a run loop.如果您使用运行循环,那么您只需要一个锁即可将消息添加到具有运行循环的线程。

pthreads are a very low-level abstraction, so there's no easy way to do this with raw pthreads. pthreads 是一个非常低级的抽象,因此使用原始 pthreads 没有简单的方法来做到这一点。 Typically you'll want to write to a file descriptor to wake up an event loop on the main thread, then pass it a pointer to the function you want to run.通常,您需要写入文件描述符以唤醒主线程上的事件循环,然后将指针传递给您要运行的 function。 You could even write pointer values onto a pipe() , then have the main thread execute them.您甚至可以将指针值写入pipe() ,然后让主线程执行它们。

To wait synchronously, you can simply have a mutex and condition variable, plus completion flag on these execution request objects.要同步等待,您可以简单地使用互斥锁和条件变量,以及这些执行请求对象上的完成标志。 Have the child thread wait on the mutex/condvar/completion flag, then in the main thread (under the mutex) set the flag and signal the cvar.让子线程等待 mutex/condvar/completion 标志,然后在主线程中(在 mutex 下)设置标志并向 cvar 发出信号。 Cleanup of the request structure would be done in the child.请求结构的清理将在孩子中完成。

To be more specific, it'd help if you could mention what event loop you have running on your main thread.更具体地说,如果您能提及您在主线程上运行的事件循环,将会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM