Advertisement
Guest User

Untitled

a guest
May 27th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import Foundation
  2.  
  3. /// Execute a function on a background thread and then handle result
  4. /// in main thread.
  5. func doBackgroundTask<Params, Result>(
  6. params: Params,
  7. backgroundTask: (Params) -> Result,
  8. onComplete: (Result) -> ())
  9. {
  10. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  11. let result = backgroundTask(params)
  12. dispatch_async(dispatch_get_main_queue()) {
  13. onComplete(result)
  14. }
  15. }
  16. }
  17.  
  18. /// Execute a procedure on a background thread and then handle result
  19. /// in main thread.
  20. func doAsyncTask<Result>(
  21. backgroundTask: () -> Result,
  22. onComplete: (Result) -> ())
  23. {
  24. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  25. let result = backgroundTask()
  26. dispatch_async(dispatch_get_main_queue()) {
  27. onComplete(result)
  28. }
  29. }
  30. }
  31.  
  32.  
  33. // Example:
  34.  
  35. func test(lo: Int, hi: Int) {
  36. doBackgroundTask((lo, hi), { (lo: Int, hi: Int) -> Int in
  37. println("(Background task running in thread \(pthread_self()))")
  38. var result = 0
  39. for i in lo...hi {
  40. println("(Step \(i) in thread \(pthread_self()))")
  41. result = result + i
  42. NSThread.sleepForTimeInterval(0.5)
  43. }
  44. return result
  45. }, { (result: Int) in
  46. println("(Completion on main thread \(pthread_self()))")
  47. println("Sum of \(lo)...\(hi) is \(result)")
  48. });
  49. }
  50.  
  51. import XCPlayground
  52.  
  53. XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
  54.  
  55. // These tests will run concurrently
  56. test(1, 5)
  57. test(10, 15)
  58. test(20, 25)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement