码迷,mamicode.com
首页 > 其他好文 > 详细

Dispatch Semaphore

时间:2014-05-28 21:51:45      阅读:395      评论:0      收藏:0      [点我收藏+]

标签:des   c   class   code   tar   a   

 

 

A dispatch semaphore(信号量) is useful if you need a concurrency control for a small portion(部分) of the source code that has smaller granularity(颗粒度) than a serial dispatch queue or dispatch_barrier_async function.

If data are updated concurrently, inconsistent(不一致的) data might occur or the application might crash. You can avoid that by using a serial dispatch queue or the dispatch_barrier_async function. But sometimes concurrency control has to be done in smaller granularity.

(其实iOS的dispatch semaphore和Windows系统的Semaphore的作用是一样的,都是用来作线程同步或者说资源的互斥访问的。当然在Windows系统下,除了Semaphore之外,CriticalSection、Event、Mutex也可以完成此功能。)

Let’s see an example to show how to add all the data to an NSMutableArray when the order is unimportant.

 

But, because the NSMutableArray class doesn’t support multithreading, when the object is updated from many threads, it will be corrupted(损坏). The application probably crashes because of a memory-related problem. This is a race condition(竞态[争]条件). We can use a dispatch semaphore in this case.

A dispatch semaphore is a semaphore with a counter. When the counter is zero, the execution waits. When the counter is more than zero, it keeps going after it decrements the counter.

The dispatch_semaphore_create function creats a dispatch semaphore.(相当于Windows系统的CreateSemaphore)

 

The argument is an initial value of the counter. As its name includes “create”, you have to release it with the dispatch_release function. You can have ownership by calling the dispatch_retain function as well.

dispatch_semaphore_wait function waits until the counter of the dispatch semaphore becomes one and more. When the counter is one and more, or the counter becomes one and more while it is waiting, it decreases the counter and returns from the dispatch_semaphore_wait function. The second argument specifies how long it waits in dispatch_time_t type. In this example, it waits forever. The return value is the same as that of the dispatch_group_wait function.

When a dispatch_semaphore_wait function returns zero, a task that needs a concurrency control can be executed safely. After finish the task, you have to call thedispatch_semaphore_signal(相当于Windows系统的ReleaseSemaphore) function to increase the counter of the dispatch semaphore by one.

整理自《Multithreading and Memory Management for iOS and OS X》

Dispatch Semaphore,布布扣,bubuko.com

Dispatch Semaphore

标签:des   c   class   code   tar   a   

原文地址:http://www.cnblogs.com/spiderdzl/p/3754563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!