识别GCD线程
我编写了一个核心数据抽象类,它保存持久存储、对象模型和对象上下文。为了使多线程更容易,我编写了对象上下文的访问器,以便它通过使用 [NSThread currentThread]
来标识线程,返回仅可用于当前线程的实例。
只要我不使用 GCD,它就可以完美工作,我想用 GCD 来替代旧的 NSThread。所以我的问题是,如何识别 GCD 线程?这个问题适用于 iOS 和 Mac OS X,但我猜这两个平台都是一样的。
I have written a Core Data abstraction class which holds the persistent store, object model and object context. To make the multithreading easier, I have written the accessor for the object context so that it returns a instance that is only available for the current thread by using [NSThread currentThread]
to identify the threads.
This works perfectly as long as I don't use GCD, which I want to use as replacement for the old NSThread's. So my question is, how do I identify a GCD thread? The question applies for both iOS and Mac OS X but I guess that its the same for both platforms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以检查dispatch_get_current_queue()是否返回任何内容。我喜欢 Jeremy 的想法,即使用队列的上下文存储转换为 CD-context-per-queue 模型,而不是 CD-context-per-thread 模型。
You could check whether dispatch_get_current_queue() returns anything. I like Jeremy's idea of transitioning to a CD-context-per-queue instead of CD-context-per-thread model using the queue's context storage though.
也许您可以在 GCD 上下文中存储每个线程的 CD 上下文 使用dispatch_set_context()
Perhaps you can store the CD context for each thread in the GCD context using dispatch_set_context()
Magical Record 中的 contextForCurrentThread 辅助方法与所说的非常相似(即每个线程保留一个上下文)。 GCD 执行块在单个队列上运行时,可能会在 GCD 管理的任何线程上运行,这将导致一些随机崩溃。查看这篇文章:http://saulmora。 com/2013/09/15/why-contextforcurrentthread-doesn-t-work-in-magicalrecord/
The contextForCurrentThread helper method in Magical Record is very similar to what to said (i.e. keep one context per thread). The GCD execution block, while running on a single queue, can potentially run on any thread managed by GCD, which will cause some random crashes. Check this article: http://saulmora.com/2013/09/15/why-contextforcurrentthread-doesn-t-work-in-magicalrecord/