Cfrunloop in Swift Command Line Program

How to prevent a Command Line Tool from exiting before asynchronous operation completes

I realize this is an old question, but here is the solution I ended on. Using DispatchGroup.

let dispatchGroup = DispatchGroup()

for someItem in items {
dispatchGroup.enter()
doSomeAsyncWork(item: someItem) {
dispatchGroup.leave()
}
}

dispatchGroup.notify(queue: DispatchQueue.main) {
exit(EXIT_SUCCESS)
}
dispatchMain()

Multiple workers in Swift Command Line Tool

I mistakenly interpreted the locking thread for a hanging program. The work will execute just fine without a run loop. The code in the question will run fine, and blocking the main thread until the whole group has finished.

So say chunks contains 4 items of workload, the following code spins up 4 concurrent workers, and then waits for all of the workers to finish:

let group = DispatchGroup()
let queue = DispatchQueue(label: "", attributes: .concurrent)

for chunk in chunk {
queue.async(group: group, execute: DispatchWorkItem() {
do_work(chunk)
})
}

_ = group.wait(timeout: .distantFuture)

Keep command line tool alive

You need to enter into a runloop using either CFRunLoop or NSRunLoop.

Try:

[[NSRunLoop currentRunLoop] run];

Swift or Objective-C command line tool and text to speech not outputting audio

NSSpeechSynthesizer.isAnyApplicationSpeaking() waits until the speech is finished.

import Foundation
import AppKit

class Speaker: NSObject , NSSpeechSynthesizerDelegate {
var synth : NSSpeechSynthesizer!

func run() {
self.synth = NSSpeechSynthesizer.init()
self.synth.delegate = self
self.synth.startSpeakingString("First word")
while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {}
}
}

var speak : Speaker = Speaker.init()
speak.run()


Related Topics



Leave a reply



Submit