简体   繁体   English

快速多线程

[英]Multithreading in swift

   func credentials() -> AWSTask<AWSCredentials> {
    var task:AWSTask<AWSCredentials>
    // let task=AWSTask<AWSCredentials>(result:nil)
    print("hello")
    let svc=ServerConnection(action: "m_get_token")
    let req=svc.createRequestWithoutBody("POST")
   let queue=DispatchQueue(label: "credentialsqueue")
    task=AWSTask<AWSCredentials>(result:nil)

    svc.getResponse(req){
        (appresp)->Void in


        print("app response data xx is \(appresp)")
        let k=appresp as? NSDictionary
        let datadict=k!["m_response_data"]! as? NSDictionary

        let kid=datadict?["AccessKeyId"]as?String
        let skid=datadict?["SecretAccessKey"]as?String
        let exp=datadict?["Expiration"]as?String
        let stoken=datadict?["SessionToken"]as?String

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let date = dateFormatter.date(from: exp!)
            DispatchQueue.main.async {
        self.cred=AWSCredentials(accessKey: kid!, secretKey: skid!, sessionKey: stoken!, expiration: date!)     
    }
    print("self.cred is \(self.cred!)")
    task=AWSTask<AWSCredentials>(result:self.cred!)
    return task
}

In the above code i set up self.cred in the secondary thread in the getResponse function....which is taking time as it's a server call.... self.cred in the main thread is returning nil as it is being executed early than before we set up in the secondary thread...how to return the value self.cred which is from the secondary thread.(don't stop main thread)User does not have to experience the delay...but nil should not be returned(value in the secondary thread should be returned). 在上面的代码中,我在getResponse函数的辅助线程中设置了self.cred ....这需要时间,因为它是一个服务器调用....主线程中的self.cred在执行时返回nil早于我们在辅助线程中设置之前...如何返回来自辅助线程的值self.cred 。(不要停止主线程)用户不必经历延迟...但是应该是不返回(应该返回辅助线程中的值)。

There are few ways to implement multi-threading in iOS: 在iOS中实现多线程的方法很少:

  • NSThread creates a new low-level thread which can be started by calling the start method. NSThread创建一个新的低级线程,可以通过调用start方法启动。

Objective C: 目标C:

    NSThread* myThread = [[NSThread alloc] initWithTarget:self
    selector:@selector(myThreadMainMethod:)object:nil];
    [myThread start];

Swift: 迅速:

var myThread = Thread(target: self, selector: #selector(self.myThreadMainMethod), object: nil)
myThread.start()
  • NSOperationQueue allows a pool of threads to be created and used to execute NSOperations in parallel. NSOperationQueue允许创建一个线程池并用于并行执行NSOperations。 NSOperations can also be run on the main thread by asking NSOperationQueue for the mainQueue. 通过向NQperationQueue询问mainQueue,也可以在主线程上运行NSOperations。

Objective C: 目标C:

    NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
    [myQueue addOperation:anOperation];
    [myQueue addOperationWithBlock:^{
         /* Do something. */
    }];

Swift: 迅速:

var myQueue = NSOperationQueue()
myQueue.addOperation(anOperation)
myQueue.addOperationWithBlock({() -> Void in
    /* Do something. */
})
  • GCD or Grand Central Dispatch is a modern feature of Objective-C that provides a rich set of methods and API's to use in order to support common multi-threading tasks. GCD或Grand Central Dispatch是Objective-C的一个现代功能,它提供了一组丰富的方法和API,以支持常见的多线程任务。 GCD provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel) or a serial queue (tasks are run in FIFO order). GCD提供了一种在主线程,并发队列(并行运行任务)或串行队列(任务以FIFO顺序运行)中对任务进行分派的方法。

Objective C: 目标C:

    dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(myQueue, ^{
       printf("Do some work here.\n");
    });

Swift: 迅速:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
dispatch_async(queue) {
}

Also Check following links for more details: 另请查看以下链接了解更多详情:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM