Multithreading in iOS-Part 2/4

(DispatchWorkItem, DispatchGroup, DispatchBarrier, DispatchSemaphore, DispatchSources)

DispatchWorkItem:-

Instead of writing code block under specific queue. You can have a block of code which can be executed on any thread

How can we cancel a work item:-

One reason why we need to use an explicit DispatchWorkItem because If we need to cancel the task before or during execution. It can be achieved by calling cancel() on the work item one of two actions will be performed:

  1. If the task is currently executing, the isCancelled property will be set to true

DispatchGroup:-

With dispatch groups we can group together multiple tasks and either wait for them to be completed or be notified once they are complete. Tasks can be asynchronous or synchronous and can even run on different queues.

  1. Call enter() to manually notify the group that a task has started. You must balance out the number of enter() calls with the number of leave() calls else your app will crash.
  2. You call wait() to block the current thread while waiting for tasks completion. You can use wait(timeout:) to specify a timeout and bail out on waiting after a specified time.
  3. Instead ofwait() or wait(timeout:) you notify the group that this work is done.
  4. At this point, you are guaranteed that all tasks have either completed or timed out. You then make a call back to the main queue to run your completion closure.
1. wait with time out 2. output

In which situations you can use DispatchGroup?

some use cases where you can use DispatchGroup are:

  • When you need to add animation as well as some network api call or database update. After these two work you need to show message and many more situations like this.
different syntax used here we can follow anything to execute code

How can you Delay the task Execution:-

DispatchQueue allows you to delay task execution. Care should be taken not to use this to solve race conditions or other timing bugs through hacks like introducing delays. Use this when you want a task to run at a specific time.

  • milliseconds
  • nanoseconds

How can we get Current Queue Name?

API provides us a function to check whether a call is in the main thread or not. But there is no way to get current queue name.

DispatchBarrier:-

Thread safe code can be called safely from multiple threads without causing any problem such as data corruption or app crash. When we use singleton or code that is not thread safe then we face problem like data corruption. We can avoid this issue by using dispatch barrier.

with dispatchBarrier
  • Global Concurrent Queue: Use caution here. This probably isn’t the best idea because other systems might be using the queues and it will block that execution until barrier code completes its execution.
  • Custom Concurrent Queue: This is a great choice for atomic or critical areas of code. Anything you’re setting or instantiating that needs to be thread-safe is a great candidate for a barrier.

DispatchSemaphore

In multithread, threads must wait for exclusive access to a resource. this is the one way to make threads wait and put them to sleep inside the kernel so that they no longer take any CPU time.

  • call signal() each time after using the shared resource. Signalling the semaphore that we are done interacting with the shared resource.
  • If the resulting value is less than zero, thread is blocked and will go into waiting state.
  • If the resulting value is equal or bigger than zero, code will get executed without waiting.
  • If the previous value was less than zero, this function unblock the thread currently waiting in the thread queue.
  • If the previous value is equal or bigger than zero, it means thread queue is empty that means no one is waiting.
without semaphore. when run this code each and every time we get different result
with semaphore- we always get result as [0, 1, 2, 3,4, 5, 6, 7, 8, 9, 10]

DispatchSources

The DispatchSource contains a series of objects that are capable of monitoring OS-related events.

  • Signal Dispatch Sources (DispatchSourceSignal): Used to handle UNIX signals.
  • Memory Dispatch Sources (DispatchSourceMemoryPressure): Used to register for notifications related to the memory usage status .
  • Descriptor Dispatch Sources (DispatchSourceFileSystemObject, DispatchSourceRead, DispatchSourceWrite): Descriptor sources sends notifications related to a various file- and socket-based operations, such as:
  1. signal when it is possible to write data
  2. files delete, move, or rename
  3. files meta information change
  1. a process issues a fork or exec type of call
  2. a signal is delivered to the process.

Let’s see some use cases:

1. DispatchSourceTimer use case

  • In this situation DispatchSourceTimer could be used. A dispatch timer source, fires an event when the time interval has been completed, which then fires a pre-set callback all on the same queue.

Note:

iOS Developer in walmart