使用GCD进行读写锁定 [英] Read-Write lock with GCD

查看:278
本文介绍了使用GCD进行读写锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序大量使用GCD,几乎所有内容都分散在由调度处理的小任务中。但是,基础数据模型主要是读取的,只是偶尔写入。

My application makes heavy use of GCD, and almost everything is split up in small tasks handled by dispatches. However, the underlying data model is mostly read and only occasionally written.

我目前使用锁来防止在阅读时更改关键数据结构。但是在今天看了一些锁之后,我发现了NSConditionLock和一些关于读写锁的页面。后者正是我所需要的。

I currently use locks to prevent changes to the critical data structures while reading. But after looking into locks some more today, I found NSConditionLock and some page about read-write locks. The latter is exactly what I need.

我发现了这个实现: http://cocoaheads.byu.edu/维基/锁。我的问题是,这个实现是否适用于GCD,看到它使用PThreads?

I found this implementation: http://cocoaheads.byu.edu/wiki/locks . My question is, will this implementation work with GCD, seeing that it uses PThreads?

推荐答案

它仍然可以使用。 pthreads是线程API,是Mac OS X上所有其他使用线程的API的基础。(在那之下有Mach线程激活,但那是SPI,而不是API。)无论如何,pthreads锁并不需要你使用pthreads线程。

It will still work. pthreads is the threading API which underlies all of the other thread-using APIs on Mac OS X. (Under that there's Mach thread activations, but that's SPI, not API.) Anyway, the pthreads locks don't really require that you use pthreads threads.

然而,从iOS 5开始,GCD提供了更好的选择: dispatch_barrier_async()。基本上,您有一个专用并发队列。您以正常方式向其提交所有读取操作。您可以使用barrier例程向其提交写入操作。当当!读写锁定。

However, GCD offers a better alternative as of iOS 5: dispatch_barrier_async(). Basically, you have a private concurrent queue. You submit all read operations to it in the normal fashion. You submit write operations to it using the barrier routines. Ta-da! Read-write locking.

如果您有权访问第210届WWDC 2011会议视频 - 掌握Grand Central Dispatch

这篇关于使用GCD进行读写锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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