简体   繁体   中英

Is serial queue(other than Main) code execute on Main thread?

1) Serial queues in ios created by

_queue = dispatch_queue_create("serial-queue-1", nil);

runs on Main thread or some different thread.

And

2) If it runs on Main thread then if we syncronously dispatch the block of code to the above queue by

dispatch_sync(_queue, ^{ method1(); method2(); });

Would it execute the complete block of code when this queue gets its turn or it can also leave this queue to execute some other in between ?

In general, a block that is dispatched on a queue can run on any available thread, including the main thread. The exception to this is that a block dispatched on the main queue will always run on the main thread.

When you use dispatch_sync on a serial queue it blocks the current queue , but not the current thread .

From the dispatch_sync documentation

Calling this function and targeting the current queue results in deadlock.

If you target the current queue using dispatch_sync you will get a deadlock, but if you target a different queue you will not get a deadlock, even if the dispatched block ends up on the same thread.

In fact:

As a performance optimization, this function executes blocks on the current thread whenever possible

So, presuming that the dispatch_sync in your question was called from the main queue, the block will run on the main thread, since you have blocked the main queue and the main thread is therefore available to perform the work.

iOS multitasking is not pre-emptive, so your block cannot "lose" the thread; the block will execute in its entirety before relinquishing the thread. This is assuming that method1 and method2 do not dispatch further blocks themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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