Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created November 27, 2015 12:58
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 rjstelling/6859d073646c107a55cc to your computer and use it in GitHub Desktop.
Save rjstelling/6859d073646c107a55cc to your computer and use it in GitHub Desktop.
Swift command line script using NSOperation.
#!/usr/bin/env xcrun swift
//
// SwiftCommandLineWithNSOperation.swift
// SwiftCommandLineWithNSOperation
//
// Created by Richard Stelling on 27/11/2015.
// Copyright © 2015 Richard Stelling. All rights reserved.
//
import Foundation
// Set up the NSOperationQueue, the higher you set maxConcurrentOperationCount
// the quicker all the operation will finish (up to 10)
var queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 5 //Deadlock if this is = 1
queue.qualityOfService = .Utility
let start = NSDate()
let outterOp = NSBlockOperation {
for i in 0..<10 {
let op = NSBlockOperation {
for j in 0..<5 {
sleep(1)
print("*", terminator: "")
fflush(__stdoutp)
}
}
queue.addOperation(op)
print("|")
sleep(2)
}
}
queue.addOperation(outterOp)
// This will block until all our operation have compleated (or been canceled)
queue.waitUntilAllOperationsAreFinished()
let end = NSDate()
let delta = end.timeIntervalSinceDate(start)
print("\n\nOperation took \(floor(delta)) wall clock seconds")
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment