Skip to content

Instantly share code, notes, and snippets.

@robertmryan robertmryan/Sample.swift
Last active Jul 12, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jul 12, 2019

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
You can’t perform that action at this time.