Skip to content

Instantly share code, notes, and snippets.

@barron9
Last active August 30, 2023 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barron9/541fe4631a39da876663fdea8a51e35c to your computer and use it in GitHub Desktop.
Save barron9/541fe4631a39da876663fdea8a51e35c to your computer and use it in GitHub Desktop.
import Foundation
class ThreadInterruptionSimulator {
var threads: [Thread] = []
var interrupterThread: Thread?
// Function to simulate work done by threads
func worker(threadNum: Int) {
// for _ in 0..<5 {
print("Thread \(threadNum) is working...")
Thread.sleep(forTimeInterval: 2)
var values: [Int] = []
// Allocate and work with an array of 100 values
for i in 0..<100 {
values.append(i)
}
if Thread.current.isCancelled {
print("Thread \(threadNum) ont annulé déjà...")
return
}
print("Thread \(threadNum) allocated and worked with values: \(values.count)")
// Assert that the array has 100 values
assert(values.count == 100, "Array does not have 100 values")
// }
}
// Function to simulate random interruptions
func interrupter() {
while true {
Thread.sleep(forTimeInterval: Double.random(in: 0.1...0.5))
let threadToInterrupt = threads.randomElement()!
if(!threadToInterrupt.isFinished){
print("Interrupting Thread \(threadToInterrupt.name ?? "")...")
threadToInterrupt.cancel()
}
}
}
// Start simulation
func startSimulation() {
// Create and start worker threads
for i in 0..<5 {
let thread = Thread {
self.worker(threadNum: i)
}
thread.name = "WorkerThread\(i)"
threads.append(thread)
thread.start()
}
// Create and start interrupter thread
interrupterThread = Thread {
self.interrupter()
}
interrupterThread?.name = "InterrupterThread"
interrupterThread?.start()
// Wait for all worker threads to complete
for thread in threads {
while !thread.isFinished {
Thread.sleep(forTimeInterval: 0.1)
}
}
// Stop the interrupter thread
interrupterThread?.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment