Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- /// Execute a function on a background thread and then handle result
- /// in main thread.
- func doBackgroundTask<Params, Result>(
- params: Params,
- backgroundTask: (Params) -> Result,
- onComplete: (Result) -> ())
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
- let result = backgroundTask(params)
- dispatch_async(dispatch_get_main_queue()) {
- onComplete(result)
- }
- }
- }
- /// Execute a procedure on a background thread and then handle result
- /// in main thread.
- func doAsyncTask<Result>(
- backgroundTask: () -> Result,
- onComplete: (Result) -> ())
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
- let result = backgroundTask()
- dispatch_async(dispatch_get_main_queue()) {
- onComplete(result)
- }
- }
- }
- // Example:
- func test(lo: Int, hi: Int) {
- doBackgroundTask((lo, hi), { (lo: Int, hi: Int) -> Int in
- println("(Background task running in thread \(pthread_self()))")
- var result = 0
- for i in lo...hi {
- println("(Step \(i) in thread \(pthread_self()))")
- result = result + i
- NSThread.sleepForTimeInterval(0.5)
- }
- return result
- }, { (result: Int) in
- println("(Completion on main thread \(pthread_self()))")
- println("Sum of \(lo)...\(hi) is \(result)")
- });
- }
- import XCPlayground
- XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
- // These tests will run concurrently
- test(1, 5)
- test(10, 15)
- test(20, 25)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement