dispatch_sync() always execute block in main thread

前端 未结 3 1119
忘了有多久
忘了有多久 2020-12-01 13:35

Is there any difference between if dispatch_sync is called in 3 different queue like

1.

 dispatch_sync(dispatch_get_main_queue(),^(void){
      NSLo         


        
3条回答
  •  长情又很酷
    2020-12-01 13:53

    See dispatch_sync documentation, which notes

    As an optimization, this function invokes the block on the current thread when possible.

    If you dispatch something synchronously, since the thread must wait for the dispatched code to complete, anyway, it will frequently run that code on the current thread. So if dispatched synchronously from the main thread, it will run on main thread. If dispatched synchronously from a background thread, it will run on that background thread.

    As noted by ipmcc, a well-known exception is when a background thread dispatches something synchronously to the main thread. As the libdispatch source says:

    It's preferred to execute synchronous blocks on the current thread due to thread-local side effects, garbage collection, etc. However, blocks submitted to the main thread MUST be run on the main thread.

提交回复
热议问题