<commit_before>---
layout: post
title: Concurrency with swift 3
---

The common concurrency issues faced are the one related to acessing and modifying the shared resource from different threads. One can think of this as a [producer-consumer problem](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem).

Consider the following simplest concurrency scenario

```swift
var items = [Int]()

//Producer:
func add(num: Int) {
    print("Add \(num)")
    items.append(num)
}
    
//Consumer:
func remove() {
    guard !items.isEmpty else {
        return
    }
   let num = items.removeLast()
   print("Remove \(num)")
}

let dispatchQueue = DispatchQueue(label: "com.prit.TestGCD.DispatchQueue", attributes: DispatchQueueAttributes.concurrent)

for x in 0..<10 {
        dispatchQueue.async {
            self.add(num: x)
        }
    }
    
for _ in 0..<10 {
    dispatchQueue.async {
        self.remove()
    }
}
```
The above code appends and removes integer 10 times in an array. Since all these calls are done in a concurrent way, one cannot predict the order in which they are executed.Thus the above code models the concurrent scenario appropriately.

Problems in the above code - Since addition and deletion occurs in concurrent way, there is the possibility of a crash, which we will inspect below.  

### Problem Inspection ###

Consider the following scenario :-

1. Nine addition blocks are already executed and just one addition block is left for execution.
2. Whereas all 8 `remove` blocks are executed and currently the last two are being executed.Thus at this point the count of `items` will be 1.
3. Due to race consition assume that the last addition block is being executed after the two `remove` blocks.

In the above scenario, since the `items` count is 1 and two remove blocks are being executed simulataneously, thus calling `removeLast` two times on an array with count 1 will lead to a crash.

The above problem can be solved in many ways, which are listed below.

## Locks ##
	
The simplest solution would be to lock the other execution blocks when `items` is being modified. 
	
```swift
 var lock = Lock()<commit_msg>fixed alignment<commit_after>---
layout: post
title: Concurrency with swift 3
---

The common concurrency issues faced are the one related to acessing and modifying the shared resource from different threads. One can think of this as a [producer-consumer problem](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem).

Consider the following simplest concurrency scenario

```swift
var items = [Int]()

//Producer:
func add(num: Int) {
    print("Add \(num)")
    items.append(num)
}
    
//Consumer:
func remove() {
    guard !items.isEmpty else {
        return
    }
   let num = items.removeLast()
   print("Remove \(num)")
}

let dispatchQueue = DispatchQueue(label: "com.prit.TestGCD.DispatchQueue", attributes: DispatchQueueAttributes.concurrent)

for x in 0..<10 {
    dispatchQueue.async {
        self.add(num: x)
    }
}
    
for _ in 0..<10 {
    dispatchQueue.async {
        self.remove()
    }
}
```
The above code appends and removes integer 10 times in an array. Since all these calls are done in a concurrent way, one cannot predict the order in which they are executed.Thus the above code models the concurrent scenario appropriately.

Problems in the above code - Since addition and deletion occurs in concurrent way, there is the possibility of a crash, which we will inspect below.  

### Problem Inspection ###

Consider the following scenario :-

1. Nine addition blocks are already executed and just one addition block is left for execution.
2. Whereas all 8 `remove` blocks are executed and currently the last two are being executed.Thus at this point the count of `items` will be 1.
3. Due to race consition assume that the last addition block is being executed after the two `remove` blocks.

In the above scenario, since the `items` count is 1 and two remove blocks are being executed simulataneously, thus calling `removeLast` two times on an array with count 1 will lead to a crash.

The above problem can be solved in many ways, which are listed below.

## Locks ##
	
The simplest solution would be to lock the other execution blocks when `items` is being modified. 
	
```swift
 var lock = Lock()
{'fraction_non_alphanumeric': 0.0768514205868654, 'fraction_numerical': 0.009781089892873778, 'mean_word_length': 3.638228941684665, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '403418', 'n_tokens_mistral': 1203, 'n_tokens_neox': 1122, 'n_words': 568}