From 816720e15ca4267c4ef41340cdf014486658b7e9 Mon Sep 17 00:00:00 2001 From: Yeo Kheng Meng Date: Sat, 29 Oct 2016 19:01:04 +0800 Subject: [PATCH] Mac uses gcd to run background thread --- Examples/SwiftSerialIM/Sources/main.swift | 27 ++++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/Examples/SwiftSerialIM/Sources/main.swift b/Examples/SwiftSerialIM/Sources/main.swift index c4ebed8..e9ec557 100644 --- a/Examples/SwiftSerialIM/Sources/main.swift +++ b/Examples/SwiftSerialIM/Sources/main.swift @@ -53,6 +53,17 @@ func printToScreenFrom(myself: Bool, characterToPrint: UnicodeScalar){ print(characterToPrint, terminator:"") } +func backgroundRead() { + while true{ + do{ + let readCharacter = try serialPort.readChar() + printToScreenFrom(myself: false, characterToPrint: readCharacter) + } catch { + print("Error: \(error)") + } + } +} + do { @@ -77,23 +88,23 @@ do { //Run the serial port reading function in another thread +#if os(Linux) var readingThread = pthread_t() let pthreadFunc: @convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? = { observer in - while true{ - do{ - var readCharacter = try serialPort.readChar() - printToScreenFrom(myself: false, characterToPrint: readCharacter) - } catch { - print("Error: \(error)") - } - } + backgroundRead() } pthread_create(&readingThread, nil, pthreadFunc, nil) +#elseif os(OSX) + DispatchQueue.global(qos: .userInitiated).async { + backgroundRead() + } + +#endif print("\nReady to send and receive messages in realtime!")