gpt4 book ai didi

swift - 如何在 Swift 中使用多线程

转载 作者:行者123 更新时间:2023-11-28 08:36:54 26 4
gpt4 key购买 nike

我有两个任务:任务 1 和任务 2。我想在 task1 完成后执行 task2。

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()
}
}

我在网上搜索过,我找到了NSLock,NSConditionLockobjc_sync_enter...我试过了,但是没有用...

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()
}
}

我还尝试了 NSConditionLockobjc_sync_enter...它不起作用。我如何在 swift 中使用 lock ?你能根据我的代码给我一个例子吗?谢谢。

PS:我不想在这里使用callback...因为我已经尝试过了,我觉得多线程更接近我的答案,谢谢。

最佳答案

我要一瘸一拐地出去,对你的程序结构做一些猜测。您的代码的第一个问题是它试图访问后台线程上的 View 。 GUI 元素应始终在主线程上访问。第二个问题是sleep:不要用它来编写并发代码。它假设异步任务将如何进行。您应该将该时间视为未知时间并使用同步模式或回叫。

由于您提到 task1() 下载 JSON,它很可能是异步的。以下是我的做法:

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)
}

关于swift - 如何在 Swift 中使用多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com