Skip to content

Instantly share code, notes, and snippets.

@SysCall97
Created April 9, 2024 06:45
Show Gist options
  • Save SysCall97/030f73e4ac608f4fcc0dfdd035af3099 to your computer and use it in GitHub Desktop.
Save SysCall97/030f73e4ac608f4fcc0dfdd035af3099 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] = []
// Function to write to the shared array in a thread-safe manner using barrier
func writeToArray(element: Int) {
concurrentQueue.async(flags: .barrier) {
sharedArray.append(element)
print("Added \(element) to array")
}
}
func readFromArray() {
concurrentQueue.sync {
print("Array contents: \(sharedArray)")
}
}
// Perform write operations using dispatch barrier
writeToArray(element: 1)
writeToArray(element: 2)
writeToArray(element: 3)
// Perform read operations sequentially
readFromArray()
readFromArray()
// Perform another write operation with a barrier
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