user2262304
user2262304

Reputation: 349

How to use multithread in Swift

I have two tasks : task1 and task2. I want to execute task2 after task1 finishes.

let globalQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

dispatch_sync(globalQueueDefault){

self.activityIndicatorView.hidden = false
self.activityIndicatorView.startAnimating()

    task1()

    sleep(6)
    dispatch_sync(globalQueueDefault) { () -> Void in

        task2()                                             
    }
}

I searched in internet, I find NSLock,NSConditionLock and objc_sync_enter...I have try them, but it doesn't work...

let lock = NSLock()
let globalQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

dispatch_sync(globalQueueDefault){

self.activityIndicatorView.hidden = false

self.activityIndicatorView.startAnimating() 

self.lock.lock()

task1()
self.lock.unlock()

sleep(6)
dispatch_sync(globalQueueDefault) { () -> Void in
self.lock.lock()
    task2() 
self.lock.unlock()                                            
}
}

I also tried NSConditionLock and objc_sync_enter...It doesn't work. How I can use lock in swift ? Could you give me a example base on my code? Thank you.

PS: I don't want to use callback here...because I have tried it, I think multithread is more closer to my answer, Thank you.

Upvotes: 1

Views: 487

Answers (1)

Mike Henderson
Mike Henderson

Reputation: 2142

I'm going out on a limp and making some guesses about your program structures. The first problem with your code is that it's trying to access a view on a background thread. GUI elements should always be accessed on the main thread. The second problem is sleep: don't use it to write concurrent code. It makes assumptions about how the asynchronous task is going take. You should treat that time as unknown and use a sync pattern or a call back.

Since you mentioned that task1() download JSON, it's likely asynchronous. Here's how I'd do it:

func task1(finish: () -> Void) {
    // Set up your connection to the website
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        // Handle the response, parse the json, etc
        ...

        // Now call the completion handler
        finish()
    }
}

func task2() {
    // Do whatever here
}

// In the function that triggers the JSON download
func downloadJSON() {
    self.activityIndicatorView.hidden = false
    self.activityIndicatorView.startAnimating()
    task1(task2)
}

Upvotes: 1

Related Questions