从另一个线程调用 CFRunLoopStop 是否安全?

发布于 2024-08-03 08:43:24 字数 420 浏览 8 评论 0原文

我的(主要是 POSIX)应用程序的 Mac 版本生成一个子线程,该子线程调用 CFRunLoopRun() 来执行事件循环(以从 MacOS 获取网络配置更改事件)。

当需要收拾东西离开时,主线程在子线程的运行循环上调用 CFRunLoopStop(),此时 CFRunLoopRun() 在子线程中返回,子线程退出,主线程(之前是阻塞等待子线程退出)才能继续。

这似乎有效,但我的问题是:这是一种安全/推荐的方法吗?特别是,从另一个线程调用 CFRunLoopStop() 是否容易导致竞争条件?据我所知,苹果的文档没有提及这个主题。

如果从主线程调用 CFRunLoopStop() 不是解决方案,那么什么是好的解决方案?我知道我可以让子线程调用 CFRunLoopRunInMode() 并经常醒来以检查布尔值或其他内容,但如果可以避免的话,我不希望子线程进行任何轮询。

The Mac build of my (mainly POSIX) application spawns a child thread that calls CFRunLoopRun() to do an event loop (to get network configuration change events from MacOS).

When it's time to pack things up and go away, the main thread calls CFRunLoopStop() on the child thread's run-loop, at which point CFRunLoopRun() returns in the child thread, the child thread exits, and the main thread (which was blocking waiting for the child thread to exit) can continue.

This appears to work, but my question is: is this a safe/recommended way to do it? In particular, is calling CFRunLoopStop() from another thread liable to cause a race condition? Apple's documentation is silent on the subject, as far as I can tell.

If calling CFRunLoopStop() from the main thread is not the solution, what is a good solution? I know I could have the child thread call CFRunLoopRunInMode() and wake up every so often to check a boolean or something, but I'd prefer not to have the child thread do any polling if I can avoid it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぽ尐不点ル 2024-08-10 08:43:24

对于 CFRunLoopStop - 如果只能在当前运行循环上安全地调用它,则无需向其传递指示要停止哪个运行循环的参数。

该参数的存在强烈表明可以使用它来停止当前运行循环以外的运行循环。

In the case of CFRunLoopStop - if it could only be called safely on the current run loop, then it would not be necessary to pass it a parameter indicating which run loop to stop.

The presence of the parameter is a strong indication that its ok to use it to stop run loops other than the current run loop.

海螺姑娘 2024-08-10 08:43:24

特别是,从另一个线程调用 CFRunLoopStop() 是否[安全]?

以下是 运行循环管理 的内容:

Core Foundation 中的函数通常是线程安全的,可以从任何线程调用。

所以也许 CFRunLoopStop 是安全的。但我确实担心他们使用“一般”这个词。我的规则是:如果苹果不说它是安全的,你就应该假设它不安全。

为了安全起见,您可能会考虑创建一个运行循环源,将其添加到运行循环中,并在结束线程时向该源发出信号。该文档还包含自定义运行循环源的示例。

In particular, is calling CFRunLoopStop() from another thread [safe]?

Here's what Run Loop Management says:

The functions in Core Foundation are generally thread-safe and can be called from any thread.

So maybe CFRunLoopStop is safe. But I do worry about their use of the word “generally”. My rule is: If Apple doesn't say it's safe, you should assume it's not.

To err on the safe side, you might consider creating a run loop source, adding that to your run loop, and signaling that source when it's time to end the thread. That same document includes an example of a custom run loop source.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文