dispatch_async 详解

iOS多线程——GCD底层探索中(dispatch_async与dispatch_sync源码) 准备工作以及源码的下载在上一篇文章中 并发函数 dispatch_async 查看源码 dispatch_async(dispatch_queue_t // dq为队列,work为任务 void dispatch_async(dispatch_queue_t dq, dispatch_block_t work) { // 临时变量,参数 dispatch_continuation_t dc = _dispatch_continuation_alloc(); uintptr_t dc_flags = 阅读详情

dispatch_async 详解

说明

作用:在调度队列上提交异步执行的块,并立即返回。

函数原型:

void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

参数:

  1. queue:提交块的队列。系统保留队列,直到块运行完成。此参数不能为空。
  2. block:要提交给目标调度队列的块。此函数代表调用者执行Block_copy和Block_release。此参数不能为空。

此函数是将块提交到调度队列的基本机制。对此函数的调用总是在提交块后立即返回,并且从不等待调用块。目标队列确定该块是相对于提交给同一队列的其他块串行调用还是并发调用。独立的串行队列相互同时处理。

dispatch_async 函数会立即返回,block会在后台异步执行。

源码分析

void dispatch_async(dispatch_queue_t dq, void (^work)(void))
{
    dispatch_async_f(dq, _dispatch_Block_copy(work),
            _dispatch_call_block_and_release);
}
// 调用了下面的方法
void dispatch_async_f(dispatch_queue_t dq, void *ctxt, dispatch_function_t func)
{
    //1、定义一个封装的block操作
    dispatch_continuation_t dc;

    // No fastpath/slowpath hint because we simply don't know
    //2、dq_width == 1表示串行,就是main queue和用户创建的串行queue
    if (dq->dq_width == 1) {
        return dispatch_barrier_async_f(dq, ctxt, func);
    }

    //如果是global queue和用户创建的并行queue则继续向下走
    //3、线程中有个dispatch_continuation_t缓存链表,如果获取到就把链表的下一个设为缓存,相当于把第一个取出来了
    dc = fastpath(_dispatch_continuation_alloc_cacheonly());
    if (!dc) {
        //4、如果没有dispatch_continuation_t缓存在堆上创建一个,并且初始化后调用_dispatch_queue_push
        return _dispatch_async_f_slow(dq, ctxt, func);
    }
    //5、初始化dispatch_continuation_t,把block封装成dispatch_continuation_t
    dc->do_vtable = (void *)DISPATCH_OBJ_ASYNC_BIT;
    dc->dc_func = func;
    dc->dc_ctxt = ctxt;

    // No fastpath/slowpath hint because we simply don't know
    //6、如果do_targetq存在,则任务有do_targetq来执行
    if (dq->do_targetq) {
        return _dispatch_async_f2(dq, dc);
    }

    //7、把dispatch_continuation_t放到queue的执行列表中
    _dispatch_queue_push(dq, dc);
}
//dispatch_continuation_t的结构,封装的一个block操作
struct dispatch_continuation_s {
    const void *do_vtable;
    struct dispatch_continuation_s *volatile do_next;
    dispatch_function_t dc_func;
    void *dc_ctxt
    dispatch_group_t dc_group;
    void *dc_data[3];
};

通过上面的方法我们可以看出,dispatch_async_f 最终将 block 封装成 dispatch_continuation_s 并调用 _dispatch_queue_push 放到对应的 queue 的执行链表结尾,global queue 是放到自己的执行链表执行,main queue 和 user queue 放到 do_targetq 的执行链表执行。

dispatch_async(dispatch_get_main_queue(), ^{})

dispatch_async(异步)和 dispatch_sync(同步)决定有没有开子线程的能力,而不是指会不会开子线程。queue 决定有没有并发的能力。开子线程我就并发,不开就串行。

所以 dispatch_async(dispatch_get_main_queue(), ^{}) 的意思是异步地在主线程按顺序执行,没有开子线程的能力。

完整详解GCD系列(一)dispatch_async;dispatch_sync;dispatch_async_f;dispatch_sync_f 为什么要写这个系列,因为百度了一下,找了很多都是些片面的Blog,拷贝来拷贝去的,写的也很粗糙。没有一个完整的可参考系列 所以,我要写这个系列,尽量把官网文档中GCD的强大功能完整的表达出来。方便自己,也方便别人,如果发现有问题,欢迎提出 阅读详情

相关推荐

Windows10下部署Heygem进行数字人生成

对于使用Heygem生成数字人,需要注意几个问题: + 需要使用Nvidia的显卡。 + 需要在Windows上进行本地部署。主要原因为客户端是Windows的,客户端对上传的视频写入硬编码的`D:\heygem_data\voice\data`目录,需要在容器上读取这些文件。 + 需要在Windows上部署Docker,将Windows的目录映射到容器中,由容器中的服务进行读取。 + 需要特别注意,一定要有D盘,这个D盘是Windows的D盘,不能是插入的USB设备后产生的D盘。 + 需要下载3个Doc

冀辉的博客 5630

iOS 多线程:『GCD』详尽总结

本文用来介绍 iOS 多线程中 GCD 的相关知识以及使用方法。这大概是史上最详细、清晰的关于 GCD 的详细讲解+总结的文章了。通过本文,您将了解到:1. GCD 简介2. GCD 任务和队列3. GCD 的使用步骤4. GCD 的基本使用(6种不同组合区别)5. GCD 线程间的通信6. GCD 的其他方法(栅栏方法:dispatch_barrier_async、延时执行方法:dispatch_after、一次性代码(只执行一次):dispatch_once、快速迭代方法:dispatch_...

Globalizationa的博客 509

Nginx健康检查实战:如何用第三方模块提升服务可用性(附详细配置)

本文深入探讨了如何通过集成第三方健康检查模块来提升Nginx的服务可用性。文章对比了Nginx默认被动检查的局限性,并详细介绍了主动健康检查的核心优势、主流模块选型,以及以nginx_upstream_check_module为例的实战部署与配置指南,帮助运维人员构建更可靠的负载均衡架构。

weixin_28331555的博客 313

iOS的同步异步,串行并行

iOS中的异步和同步: dispatch_async(异步)和dispatch_sync(同步): 决定有没有开子线程的能力,而不是指会不会开子线程。queue 决定有没有并发的能力。开子线程我就并发,不开就串行。 dispatch_async(异步)有开子线程能力。 dispatch_sync(同步)没有开子线程能力。 1.dispatch_async各种搭配后代码块中代码在什么线程中,怎样执行? 1):dispatch_get_main_queue 都在主线程中按顺序执行(比较特殊);

程序猿老樊的博客 2018

Slurm集群调度策略详解(1)-主调度

Slurm调度系统中针对作业的调度主要有三种,主调度,回填调度,GANG调度,这篇文章主要针对主调度进行解析。

h_m_l的博客 6034

M×N扫描序列图像拼接、大视场图像拼接、全景图像拼接、2D网格拼图方法、累计误差消除(显微图像/航拍图像等)

M×N序列图像完整拼接方法前言一、最朴实的一般方法二、广度优先搜索算法1.引入库2.读入数据整体路径优化算法 前言 1、网上有很多介绍图像两两拼接的算法,但是缺少对M×N张子图两两相对位置关系获得整体误差较小,肉眼下无明显错位的完整图像的算法实现。 2、由于拼接算法的不稳定可能会产生不同程度的误差,那么如何需要选择(搜索)误差较小拼接路径。 一、最朴实的一般方法 示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。 二、广度优先搜索算法 1.引入库 代码如下(示

qq_37764141的博客 5417

常用的方法几个dispatch_async方法

为了避免界面在处理耗时的操作时卡死,比如读取网络数据,IO,数据库读写等,我们会在另外一个线程中处理这些操作,然后通知主线程更新界面。 用GCD实现这个流程的操作比前面介绍的NSThread NSOperation的方法都要简单。

Holothurian 5644

中国银行信息科技岗位笔试

收到笔试只剩四天了,收集的资料,后续会更新

weixin_46050242的博客 4612

GCD源码吐血分析(2)——dispatch_async/dispatch_sync/dispatch_once/dispatch group

上一章中,我们知道了获取GCD queue的底层实现。获取到queue后,就需要将任务提交到queue中进行处理。 我们有两种方式提交任务: dispatch_async和dispatch_sync。一个是异步不等待任务完成就返回,另一个是同步任务,需要等待任务完成。这两种提交任务的方式有所不同: dispatch_async :底层运用了线程池,会在和当前线程不同的线程上处理任务。 di...

无忘无往 8152

LangChain 单智能体与多智能体编排模式总结

LangChain的智能体系统是一个强大的框架,允许语言模型(LLMs)通过工具与外部环境交互,从而完成复杂任务。

1.大规模企业集群服务开发和服务架构设计,性能优化等经验。 2.企业级数据仓库0-1落地经验。 1618

面试真题集(十六):TensorRT基础

TensorRT面试真题解析:从模型优化到推理部署 本文精选了14道TensorRT面试题,涵盖选择题、简答题和场景题,深度考察推理工程师对TensorRT核心技术的理解。内容聚焦三个关键维度: 基础概念 FP16推理中Softmax层为何需保持FP32(数值稳定性) INT8校准原理(EntropyCalibrator2的鲁棒性优势) Plugin V3接口的构建/运行分离设计 性能优化 Conv-BN-ReLU融合减少40-60%延迟的关键机制(访存优化) 动态Shape配置策略(min/opt/max

PeterPan的博客 81

dispatch_async_f 详解

之前面试的时候被问过一个问题:你知道dispatch_async_f 吗?我一脸蒙比,问题好变态,太偏了吧,见过但是没用过,不知道干啥的。。今天一时兴起,想了解一下,下面是参数的官方文档: context: The application-defined context parameter to pass to the function.         work:      The appl

gaoyuqiang30的博客 2805

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

dispatch_barrier_GCD学习之dispatch_barrier_async详解

dispatch_barrier_async在访问数据库或文件时,使用Serial Dispatch Queue可避免数据竞争的问题。写入处理确实不可与其他的写入处理以及包含读取处理的其他某些问题并行执行。但是如果读取处理只是与读取处理并行执行,那么多个并行执行就不会发生问题。为了高效率地进行访问,读取处理追加到Concurrent Dispatch Queue中,写入处理在任一个读取处理没有执行...

weixin_36180471的博客 2015

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

dispatch_group_async 使用详解

dispatch_group_async可以实现监听一组任务是否完成,完成后得到通知执行其他的操作。这个方法很有用,比如你执行三个下载任务,当三个任务都下载完成后你才通知界面说完成的了。下面是一段例子代码: [cpp] dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ...

weixin_33851604的博客 781

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

完整详解GCD系列(一)dispatch_async;dispatch_sync;dispatch_

为什么要写这个系列,因为百度了一下,找了很多都是些片面的Blog,拷贝来拷贝去的,写的也很粗糙。 所以,我要写这个系列,尽量把官网文档中GCD的强大功能完整的表达出来。方便自己,也方便别人,如果发现有问题,欢迎提出 本教程的计划:在完整的看过GCD的官方文档之后,我实在想不出来如何用一...

chunqingtai2922的博客 265

完整详解 swift GCD系列(一)dispatch_async;dispatch_sync;dispatch_async_f;dispatch_sync_f

为什么要写这个系列,因为百度了一下,找了很多都是些片面的Blog,拷贝来拷贝去的,写的也很粗糙。 所以,我要写这个系列,尽量把官网文档中GCD的强大功能完整的表达出来。方便自己,也方便别人,如果发现有问题,欢迎提出 本教程的计划:在完整的看过GCD的官方文档之后,我实在想不出来如何用一篇文章详细完整的写出来如此多的功能。 所以,决定开一个专栏来写这个教程。计划8篇文章,分别介

ruglcc's blog 5260

iOS学习笔记74-完整详解GCD系列(一)dispatch_async;dispatch_sync;dispatch_async_f;dispatch_sync_f

为什么要写这个系列,因为百度了一下,找了很多都是些片面的Blog,拷贝来拷贝去的,写的也很粗糙。 所以,我要写这个系列,尽量把官网文档中GCD的强大功能完整的表达出来。方便自己,也方便别人,如果发现有问题,欢迎提出 本教程的计划:在完整的看过GCD的官方文档之后,我实在想不出来如何用一篇文章详细完整的写出来如此多的功能。 所以,决定开一个专栏来写这个教程。计划8篇文章,分别介

探路者_iOS 1308

dispatch_sync和dispatch_async的区别

dispatch_sync 线程同步、dispatch_async线程异步 比如 //同步 dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"dispatch_sync - 1"); }); dispa...

鸿鹄当高远 373

dispatch_async & dispatch_sync

博客搬家咯~http://joeleee.github.io/ 博客搬家咯~http://joeleee.github.io/ 博客搬家咯~http://joeleee.github.io/ Clear that! dispatch_async 是将block发送到指定线程去执行,当前线程不会等待,会继续向下执行。 dispatch_sync 也是将block发送到指定...

weixin_30685047的博客 256

GCD 异步编程实战:dispatch_async 与 dispatch_sync 的完整使用教程

Grand Central Dispatch(GCD)是 libdispatch 项目提供的强大并发编程框架,通过优化线程管理和任务调度,帮助开发者充分利用多核硬件性能。作为苹果生态系统的核心组件,GCD 提供了简洁高效的 API 来处理异步任务,其中 **dispatch_async** 和 **dispatch_sync** 是最基础也最常用的两个函数。本文将通过实例详解这两个函数的使用场景、

gitblog_00514的博客 461

dispatch_async

dispatch_asyncSubmits a block for asynchronous(异步) execution on a dispatch queue and returns immediately.block提交后立马调用这一功能,不会等block被唤醒 声明 void dispatch_async( dispatch_queue_t queue, dispatch_block_t

onebutterfly 577
上一篇: ViewController 的常用跳转及返回方法
下一篇: Leetcode3190. 使所有元素都可以被 3 整除的最少操作数
UestcXiye
博客等级 码龄8年 9047粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址