博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
dispatch_sync
阅读量:6679 次
发布时间:2019-06-25

本文共 1587 字,大约阅读时间需要 5 分钟。

dispatch_sync does two things:

  1. queue a block 
  2. blocks the current thread until the block has finished running

Given that the main thread is a serial queue (which means it uses only one thread), the following statement:

 

will cause the following events:

  1. dispatch_sync queues the block in the main queue.
  2. dispatch_sync blocks the thread of the main queue until the block finishes executing.
  3. dispatch_sync waits forever because the thread where the block is supposed to run is blocked. 

The key to understanding this is that dispatch_sync does not execute blocks, it only queues them. Execution will happen on a future iteration of the run loop.

The following approach:

 

I know where your confusion comes from:

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

Careful, it says current thread.

Thread != Queue

A queue doesn't own a thread and a thread is not bound to a queue.

 

 

I found this in :

Do not call the dispatch_sync function from a task that is executing on the same queue that you pass to your function call. Doing so will deadlock the queue. If you need to dispatch to the current queue, do so asynchronously using the dispatch_async function.

Also, I followed the link that you provided and in the description of dispatch_sync I read this:

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

So I don't think it's a problem with GCD, I think the only sensible approach is the one you invented after discovering the problem.

 https://stackoverflow.com/questions/10984732/why-cant-we-use-a-dispatch-sync-on-the-current-queue

转载地址:http://lonao.baihongyu.com/

你可能感兴趣的文章
金融单词 (整理中)
查看>>
React笔记-事件注册
查看>>
SQL 参数化查询---转
查看>>
css清除浮动float的三种方法总结
查看>>
java中关于AtomicInteger的使用
查看>>
CSS ::before 和 ::after 伪元素用法
查看>>
三栏布局 中栏实现自适应宽度
查看>>
Javascript模块化编程(二):AMD规范 (转)
查看>>
Linux系统入门教程:如何在 Linux 中修改默认的 Java 版本
查看>>
采用完成端口(IOCP)实现高性能网络服务器(Windows c++版)
查看>>
Android开发问题集合
查看>>
Unresolved import *** (models) error on Eclipse
查看>>
拖拽排序 原理+代码
查看>>
每各一秒 打印数组中的 数据
查看>>
JSON中的[]和{}
查看>>
SVM(三),支持向量机,线性不可分和核函数
查看>>
Ionic 常用插件
查看>>
Listener监听器详解(转)
查看>>
多个JavaScript库使用 $ 号的命名冲突问题
查看>>
String 方法
查看>>