Reputation: 161
I'm reading Apple's document Concurrent Programming Guide, and I think of that OperationQueue is a serial of operations. The document said we don't use locks in NSOperationQueue most of the cases.
Question
How to implement Read&Write tasks with NSOperationQueue?
When to use locks in NSOperationQueue?
Upvotes: 2
Views: 1211
Reputation: 90521
Operation queues are not necessarily serial queues. You can make an operation queue into a serial queue by calling [queue setMaxConcurrentOperationCount:1]
on it. Otherwise, by default, NSOperationQueue
s are concurrent.
You should generally design the operations that you submit to queues so that they don't require locks. That's your responsibility. The idea is that operations should be self-contained. They should be configured with the data they need to operate before they are submitted to run. That data should be a private copy; it shouldn't be something that the operation is accessing at the same time that other stuff is also accessing it. While the operation is running, it should only work with its private data and should not access other parts of the program. When the operation has completed, it should make its results available to the rest of the program. (This could be passive, by just storing its results in one of its own properties. Then, other parts of the program which may have observed the operation's completion can read it. Or it could be active, where the last thing the operation does it call some other object and send it its results.)
NSOperationQueue
doesn't provide support for read-write locking. You can use the pthread_rwlock
API for that. But another way is to use GCD dispatch queues with barrier tasks. Create a private concurrent queue using dispatch_queue_create()
. Submit read tasks to it with dispatch_[a]sync()
. Submit write tasks to it using dispatch_barrier_[a]sync()
.
Upvotes: 10