Skip to content

Instantly share code, notes, and snippets.

@SysCall97
Last active April 9, 2024 07:24
Show Gist options
  • Save SysCall97/bb06ac5d2de55964c1d55b2c216e747f to your computer and use it in GitHub Desktop.
Save SysCall97/bb06ac5d2de55964c1d55b2c216e747f to your computer and use it in GitHub Desktop.
import Foundation
// Create a custom concurrent queue
let concurrentQueue = DispatchQueue(label: "com.example.concurrentQueue", attributes:.concurrent)
var sharedArray: [Int] = []
let numberOfThreadsAllowedToAccessSharedReource: Int = 1
// Semaphore to control access the shared resource
let semaphore = DispatchSemaphore(value: numberOfThreadsAllowedToAccessSharedReource)
// Function to write to the shared array in a thread-safe manner using semaphore
func writeToArray(element: Int) {
semaphore.wait()
defer {
semaphore.signal()
}
concurrentQueue.async {
sharedArray.append(element)
print("Added \(element) to array")
}
}
func readFromArray() {
semaphore.wait()
defer {
semaphore.signal()
}
concurrentQueue.sync {
print("Array contents: \(sharedArray)")
}
}
// Perform write operations using dispatch semaphore
writeToArray(element: 1)
writeToArray(element: 2)
writeToArray(element: 3)
// Perform read operations sequentially
readFromArray()
readFromArray()
// Perform another write operation with semaphore
writeToArray(element: 4)
// Perform read operations again
readFromArray()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment