DispatchSemaphore in swift

Updated 31 August 2022


DispatchSemaphore gives us the ability to control access to a shared resource by multiple threads

According to Apple:-

An object that controls access to a resource across multiple execution contexts through the use of a traditional counting DispatchSemaphore.

Swift language has multiple threads. which means many operations and tasks are executed parallel.

which may or may not access shared resources at the same time.

If multi-threads do not access shared resources at the same time then the state of the program work as desired behavior from the program.

However, if multi-threads do access shared resources at the same time, then obviously unexpected behavior will happen like:- crashes.

Workflow of DispatchSemaphore

DispatchSemaphore allows only one thread to access shared resources at a time.

And the order of uses of resources is (FIFO), who asks first get the resource first.

Semaphores contain threads queues and a counter value integer type.

Thread queue: it is used to keep track of waiting threads in the queue in FIFO order.

Counter Value: it is used to decide if a thread should get access to a shared resource or not. The counter value changes when we call signal() or wait() function.

Then, when we call signal() and wait() function?

wait() : This function calls each time before using the shared resource. the thread asks the semaphore if the shared resource is available or not. If not, the thread will wait.

signal() : every time after using the shared resource. the function will signal the semaphore that threads are done interacting with the shared resource.

flow chart of DispatchSemaphore

Example of DispatchSemaphore

Firstly, we create a concurrent queue. this queue will be used for executing our movie downloading blocks of code.

Secondly, we create a semaphore, we decided to download 3 movies at a time so we set the semaphore with an initial counter value of 3

Third, we iterate 12 times using a for loop. On each iteration we do the following: wait() → download movie → signal()

In conclusion, we have learned about concurrency , semaphore

Lastly, please comment your thoughts and queries below.

For more blogs please click here

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home