从另一个线程调用CFRunLoopStop是安全的吗? [英] Is it safe to call CFRunLoopStop from another thread?

查看:802
本文介绍了从另一个线程调用CFRunLoopStop是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



当需要打包并离开时,主线程在子线程的运行循环上调用CFRunLoopStop(),此时CFRunLoopRun()在子线程中返回,子线程退出,主线程(阻塞等待子线程退出)可以继续。



这似乎工作,但我的问题是:这是一个安全/推荐的方式?特别是,从另一个线程调用CFRunLoopStop()可能导致竞争条件?如果从主线程调用CFRunLoopStop()不是解决方案,什么是好的解决方案?我知道我可以让子线程调用CFRunLoopRunInMode(),并经常唤醒检查一个布尔值或某事,但我不想让子线程做任何轮询,如果我可以避免它。

解决方案


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


以下是运行循环管理说:


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


所以也许CFRunLoopStop是安全的。但我担心他们使用一般一词。我的规则是:如果苹果不说它是安全的,你应该认为它不是。



为了安全起见,你可以考虑创建一个运行循环源,将它添加到你的运行循环中,并在它结束线程的时候发出信号。同一文档包括自定义运行循环源的示例。


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.

解决方案

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.

这篇关于从另一个线程调用CFRunLoopStop是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆