Last active
April 9, 2024 07:24
-
-
Save SysCall97/bb06ac5d2de55964c1d55b2c216e747f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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