Created
April 9, 2024 06:45
-
-
Save SysCall97/030f73e4ac608f4fcc0dfdd035af3099 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] = [] | |
// 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