简体   繁体   English

Swift 执行队列

[英]Swift Execution Queue

For example.例如。 I have Three background task.我有三个后台任务。 Currently running three threads and in threads is a code当前运行三个线程,在线程中是一个代码

Dispatchqueue.main.async { 
  //SOMETHING CODE
}

Can code in three different threads be executed simultaneously where there is Dispatchqueue.main.async ?可以在有Dispatchqueue.main.async地方同时执行三个不同线程中的代码吗? Thank you!谢谢!

The main queue is serial, so only one thing at a time will run on it.主队列是串行的,因此一次只能在其上运行一件事。 If multiple blocks are submitted to the main queue at the same time, they'll run sequentially.如果多个块同时提交到主队列,它们将按顺序运行。

As a rule, you should avoid thinking about this in terms of threads.通常,您应该避免从线程的角度考虑这一点。 Threads are generally an implementation detail that queues live on top of.线程通常是队列所在的实现细节。 (If you're actively creating your own threads, using pthreads for example, you should generally avoid that, and use queues.) Threads and queues are not one-to-one, except for the main thread and main queue, which are tied to each other. (如果您正在主动创建自己的线程,例如使用 pthreads,您通常应该避免这种情况,并使用队列。)线程和队列不是一对一的,除了主线程和主队列,它们是绑定的对彼此。

This matters because you generally do not "run code on a thread."这很重要,因为您通常不会“在线程上运行代码”。 You dispatch a block to a queue, and GCD will schedule that block onto some thread.您将一个块分派到一个队列,GCD 会将该块调度到某个线程上。 When you see it that way, then how the main queue behaves should become much clearer.当您以这种方式看到它时,主队列的行为应该变得更加清晰。

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

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