Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active July 12, 2019 04:32
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 robertmryan/0c66b0fd4e87339a056018a118e8ab41 to your computer and use it in GitHub Desktop.
Save robertmryan/0c66b0fd4e87339a056018a118e8ab41 to your computer and use it in GitHub Desktop.
class ViewController: NSViewController {
@IBOutlet var threadAValueLabel: NSTextField!
@IBOutlet var threadBValueLabel: NSTextField!
var threadAGoNoGo = 0
var threadBGoNoGo = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Call Async Task
startProgram()
}
@IBAction func threadAStartButton(_ sender: NSButtonCell) {
threadAGoNoGo = 1
threadAValueLabel.stringValue = "Start"
}
@IBAction func threadAStopButton(_ sender: NSButton) {
threadAGoNoGo = 0
threadAValueLabel.stringValue = "Stop"
}
@IBAction func threadBStartButton(_ sender: NSButton) {
threadBGoNoGo = 1
threadBValueLabel.stringValue = "Start"
}
@IBAction func threadBStopButton(_ sender: NSButton) {
threadBGoNoGo = 0
threadBValueLabel.stringValue = "Stop"
}
func changethreadALabel(_ message: String) {
threadAValueLabel.stringValue = message
}
func changethreadBLabel(_ message: String) {
threadBValueLabel.stringValue = message
}
func startProgram() {
// Start counting through 200 when Thread A start button is pressed and stop when Thread A Stop button is pressed. When reaching 200, go back to 0 and loop forever
DispatchQueue(label: "Start Thread A").async {
while true { // Loop Forever
var stepA = 1
while stepA < 200 {
//for _ in 1...10000000{} // Delay loop
Thread.sleep(forTimeInterval: 1) // Better to just sleep than spin
if DispatchQueue.main.sync(execute: { return self.threadAGoNoGo }) == 1 {
print("Thread A \(stepA)")
DispatchQueue.main.async {
self.changethreadALabel("North \(stepA)") // Update Thread A value display label
}
stepA += 1
}
}
stepA = 1
}
}
// Start counting through 200 when Thread B start button is pressed and stop when Thread B Stop button is pressed. When reaching 200, go back to 0 and loop forever
DispatchQueue(label: "Start Thread B").async {
while true { // Loop Forever
var stepB = 1
while stepB < 200 {
// for _ in 1...10000000{} // Delay loop
Thread.sleep(forTimeInterval: 1) // Better to just sleep than spin
if DispatchQueue.main.sync(execute: { return self.threadBGoNoGo }) == 1 {
print("Thread B \(stepB)")
DispatchQueue.main.async {
self.changethreadBLabel("South \(stepB)") // Update Thread B value display label
}
stepB += 1
}
}
stepB = 1
}
}
}
}
@robertmryan
Copy link
Author

There are better ways to sync the access of the threadAGoNoGo and threadBGoNoGo, but I was trying to do the minimal changes to make your code correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment