iOS 多线程 必谈之GCD

【iOS】多线程问题总结--GCD 在 iOS 开发过程中,我们一般在主线程里边进行 UI 刷新,例如:点击、滚动、拖拽等事件。我们通常把一些耗时的操作放在其他线程,比如说图片下载、文件上传等耗时操作。而当我们有时候在其他线程完成了耗时操作时,需要回到主线程,那么就用到了线程之间的通讯。 阅读详情

早期文章搬家, 原文链接

GCD (Grand Gentral Dispatch):存在于libdispatch 中,是一套基于C的API,函数功能灰常强大

一、dispatch queue

  • 首先引入两个概念:
    • 1.任务:执行的操作
    • 2.队列:存放任务的
  • 队列的类型:
    • 1.并发队列
      • 自己创建:dispatch_queue_create()
      • 全局并发队列:dispatch_get_global_queue()
// 创建并发队列
   dispatch_queue_t queue1 = dispatch_queue_create("com.JY", DISPATCH_QUEUE_CONCURRENT);
// 获取全局并发队列
dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
  • 2.串行队列
    • 自己创建:dispatch_queue_create()
// 手动创建串行队列
dispatch_queue_t queue = dispatch_queue_create("com.JY", DISPATCH_QUEUE_SERIAL);
  • 3.主队列
// 获取当前主队列
dispatch_queue_t queue1 = dispatch_get_main_queue();
  • 同步异步函数:
    • 同步函数:不具备开启新线程的能力,只能是在当前线程执行。
    • 异步函数:具备开启新线程的能力,可以在新线程执行
// 此处的queue为队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
     // 需要执行的任务
     NSLog(@"---------%@", [NSThread currentThread]); 
});
dispatch_sync(queue, ^{
     NSLog(@"---------%@", [NSThread currentThread]);
});
  • 由上可以总结出:并发队列只有在异步函数才并发执行任务

  • 可能会有人说 dispatch_get_global_queue(0, 0); 此处的两个参数该填写的问题:前者是有关队列的优先级别的,后面参数暂时没用可用0代替即可。

  • 优先级可这样定义 dispatch_queue_priority_t priroity jump into defination 会发现所有的优先级

  • 总结:各队列执行效果

全局并发队列创串行队列主队列
同步(sync)没有开启新线程,串行执行任务没有开启新线程,串行执行任务没有开启新线程,串行执行任务
异步(async)开启新线程,并发执行任务开启新线程,串行执行任务没有开启新线程,串行执行任务
  • 注意:当使用同步函数,往__当前__*串行队列*中添加任务,会卡住当前串行队列

###二、线程间的通信

  • 此处引入一下GCD牛逼的地方

    • GCD 可以提高CPU的利用率(适应CPU的多核发展)
    • GCD 会自动管理线程的生命周期(创建,调度,销毁)
    • Coder 只需要让GCD去执行任务,不需要编写线程管理代码
  • 我们把下载的一些操作放入子线程中,势必会遇到线程中的通信问题(某些操作是必须在主线程刷新的,比如UI刷新)

  • 还可以 performSelectorOnMainThread: withObject: waitUntilDone: 回到主线程

// 图片的网络路径
NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/baike/c0%3Dbaike150%2C5%2C5%2C150%2C50/sign=db9486a9d639b60059c307e588395e4f/b90e7bec54e736d1e174094298504fc2d5626911.jpg"];
// 显示图片
        
// 主线程刷新
   dispatch_async(dispatch_get_main_queue(), ^{
            
          self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        });
    });

三、延时执行 dispatch_after:

  • 告诉线程,从现在开始延迟2秒后再执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"run-----");
        });

四、栅栏 dispatch_barrier_async

  • 在栅栏之前的多条线程执行完成之后再执行,栅栏后的多条线程
- (void)barrier
{
    dispatch_queue_t queue = dispatch_queue_create("com.JY", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        NSLog(@"----1-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"----2-----%@", [NSThread currentThread]);
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"----barrier-----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"----3-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"----4-----%@", [NSThread currentThread]);
    });
}

五、once

六、group dispatch_group_t (分组)

  • 应用场景:当遇到需要等两个线程执行完成之后,才能执行最后一个线程的任务
  • 此处以下载两张图片并合成为例,只有下载完成之后才能执行合成操作
  • 分析:
    • 1.创建一个队列组
    • 2.开启两条 dispatch_group_async 线程下载
    • 3.合成 dispatch_group_notify (等aysnc 执行完成后才会来到这个任务)
- (void)group
{
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 创建一个队列组
    dispatch_group_t group = dispatch_group_create();
    
    // 1.下载图片1
    dispatch_group_async(group, queue, ^{
        // 图片的网络路径
        NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
        
        // 加载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        // 生成图片
        self.image1 = [UIImage imageWithData:data];
    });
    
    // 2.下载图片2
    dispatch_group_async(group, queue, ^{
        // 图片的网络路径
        NSURL *url = [NSURL URLWithString:@"http://pic38.nipic.com/20140228/5571398_215900721128_2.jpg"];
        
        // 加载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        // 生成图片
        self.image2 = [UIImage imageWithData:data];
    });
    
    // 3.将图片1、图片2合成一张新的图片
    dispatch_group_notify(group, queue, ^{
        // 开启新的图形上下文
        UIGraphicsBeginImageContext(CGSizeMake(250, 250));
        
        // 绘制图片
        [self.image1 drawInRect:CGRectMake(0, 0, 125, 250)];
        [self.image2 drawInRect:CGRectMake(125, 0, 125, 250)];
        
        // 取得上下文中的图片
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        
        // 结束上下文
        UIGraphicsEndImageContext();
        
        // 回到主线程显示图片
        dispatch_async(dispatch_get_main_queue(), ^{
            // 4.将新图片显示出来
            self.imageView.image = image;
        });
    });
}

六、applay (快速迭代)

  • 应用场景: 快速迭代
  • 此处以复制文件为例
    • 剪切文件需要的是拿到文件夹的全路径
    • 大量文件复制其实也是耗时操作
    • [mgr subpathsAtPath:from] 获得文件夹下的所有文件名,返回值为数组
    • dispatch_apply 中block 有个索引 可以打印出来看看
- (void)apply
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 源路径
    NSString *from = @"";
    // 目标路径
    NSString *to = @"";
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 从文件中获取文件内容
    NSArray *subpaths = [mgr subpathsAtPath:from];
    
    dispatch_apply(subpaths.count, queue, ^(size_t index) {
        NSString *subpath = subpaths[index];
        NSString *fromFullpath = [from stringByAppendingPathComponent:subpath];
        NSString *toFullpath = [to stringByAppendingPathComponent:subpath];
        // 剪切
        [mgr moveItemAtPath:fromFullpath toPath:toFullpath error:nil];
        
        NSLog(@"%@---%@", [NSThread currentThread], subpath);
    });
}
  • 文件剪切的方法
   NSString *from = @"";
    NSString *to = @"";
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    NSArray *subpaths = [mgr subpathsAtPath:from];
    
    for (NSString *subpath in subpaths) {
        NSString *fromFullpath = [from stringByAppendingPathComponent:subpath];
        NSString *toFullpath = [to stringByAppendingPathComponent:subpath];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 剪切
            [mgr moveItemAtPath:fromFullpath toPath:toFullpath error:nil];
        });
    }

###七、GCD 计时器

  • 可能大家都觉得都有 NSTimer 计时器了,为什么此处还要引入GCD定时器呢。
  • 答:NSTimer 计时精度没有GCD高,容易受RunLoop 模式(Mode)影响,默认是在NSDefaultRunLoopMode模式下执行,当切换到UITrackingRunLoopModeMode 就不不会执行了。那么现在就有必要引入GCD定时器了!
  • 定时器创建:
    • dispatch_source_t 其实是一个OC 类奥,所以要定义一个强引用。
// 说好的是OC 类为啥timer不带* 呢,因为dispatch_source_t 自带*
@property (nonatomic, strong) dispatch_source_t timer;
  • 定时器创建完了,还要设置属性,设置回调,开启
// 获得队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    // 创建定时器dispatch_source_create(dispatch_source_t本质还是个OC对象)
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//    NSLog(@"%@", self.timer);
    
    // 设置定时器的各种属性
    dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 4.0 * NSEC_PER_SEC), 2.0 * NSEC_PER_SEC, 0);
    
    // 设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"JY is running");
        
    });
    // 启动定时器
    dispatch_resume(self.timer);
  • 刚刚说GCD定时器定时精度高,不是吹,看看NSEC_PER_SEC微秒就知道了
  • 说了这么多,光是让他跑了,怎么结束呢。
dispatch_cancel(self.timer);
iOS 多线程-GCD栅栏方法 上一篇文章记录了队列组的使用,是为了处理多个任务之间的顺序。但是开发中会出现多组任务的顺序问题。 例如:现在有两组任务,每组任务中有多个任务需要并发处理,但是两组任务之间需要顺序执行。这个时候需要用到GCD多线程处理的另一种方式:栅栏方法(dispatch_barrier_async)。 栅栏方法(dispatch_barrier_async) 栅栏方法:就是像筑起一个栅栏一样,将队列中的多组线程... 阅读详情

相关推荐

深入掌握iOS GCD多线程编程

本文还有配套的精品资源,点击获取 简介:GCD(Grand Central Dispatch)是iOS多线程编程的高效工具,简化了并发编程的复杂性,提供了灵活的异步执行机制。本教程详细介绍了GCD的基本概念、队列类型、任务提交方式以及工作模式,并通过示例讲解了如何创建队列、提交任务、延迟执行、实现栅栏任务以及使用小组件来跟踪任务。同时,提供了GCD最佳实践建议,如避免主线程...

weixin_42601608的博客 1009

ios xcode 怎样模拟app被挂起(在后台被系统杀死) APP 的五种状态

点击xcode中的stop键后,这时app就处于挂起状态

baidu_40537062的博客 2147

GCD异步获取图片

GCD异步获取图片

IOS GCD Timer

GCD中的Timer GCD中的Timer应该是最灵活的,而且是多线程的。GCD中的Timer是靠Dispatch Source来实现的。 因此先需要声明一个dispatch_source_t本地变量: @interface ViewController () {     dispatch_source_t _timer; }   接着通过dispa

指尖◎假如 6159

ddr3ip核心_DDR3 IP 核配置

DDR3 控制器 IP 核2.DDR3 IP核配置点击 Flow Navigator 面板下的“Project Manager -->IP Catalog”。 在“Memories & Storage Elements -->Memory Interface Generators”分类展开后,可以看到名为“Memory Interface Generator (MIG 7 ...

weixin_33049919的博客 2942

用c++生成随机迷宫_自动生成随机迷宫(1)prim算法

“程序 = 数据 + 算法”,一款好的作品不单单是代码的堆砌,还有其灵魂的部分,那就是算法;算法是一系列解决问题的清晰指令,算法代表着用系统的方法描述解决问题的策略机制。算法既然是解决某类型问题的规范,那么我们就学习它,并在我们的作品中使用它。从这一期开始做一个迷宫系列,包括用算法生成随机迷宫,用算法自动寻址走迷宫。 三大迷宫生成算法之一“随机Prim算法不是...

weixin_31787547的博客 2602

IOS对于线程队列的一些理解

第一部分:线程与队列 线程是代码执行的路径,队列则是用于保存以及管理任务的,线程负责去队列中取任务进行执行。 例如:在主线程调用如下代码 dispatch_sync(queue, ^{             task()           });  task函数这个任务将会提交到队列queue上,主线程负责去执行这个任务。 可以在task函数中log日志查看

jacky_jin的专栏 4156

30分钟上手TI DRV89xx-Q1EVM:多通道电机驱动器评估板实战指南

多通道H桥电机驱动器是机器人、工业自动化及汽车电子中实现多轴运动控制的核心器件,其核心原理是通过集成多个半桥电路,利用SPI通信与PWM调制技术,实现对多个直流电机或负载的独立、精确驱动。这类技术方案能显著减少外围元件数量与PCB面积,提升系统集成度与可靠性,在关节机器人、精密座椅调节及多轴控制单元等场景中价值突出。本文以德州仪器DRV89xx-Q1系列评估板为例,深入解析其硬件架构、安全操作规范及图形化软件配置流程,重点涵盖**过流保护**与**PWM频率**等关键参数的设置与调试,帮助工程师快速完成从硬

weixin_29192141的博客 348

GCD2-当前线程

什么情况,block{}内当前线程为主线程? 简单回答:dispatch_get_main_queue()调用; 总结:不管是同步或异步调用,在系统主队列main queue调用,block即{}内当前线程[NSThread currentThread]是主线程,而非自定义的串行队列调用不是在主线程;本人已经测试过。 ...

lcx_love_yx的专栏 532

​​​​手把手教你玩转RT-Thread操作系统专栏--​​​​第5章 设备驱动开发:RT-Thread的设备框架​​​​5.4 I2C/SPI驱动:如何驱动外部传感器(以MPU6050为例)​

通过本节学习,掌握了基于RT-Thread设备模型的I2C/SPI驱动开发流程,包括硬件初始化、寄存器读写、设备注册及应用程序调用。I2C(Inter-Integrated Circuit)和SPI(Serial Peripheral Interface)是嵌入式系统中最常用的两种串行总线协议,广泛用于连接传感器、存储器等外设。函数通过I2C协议读取外设寄存器的数据(如MPU6050的加速度寄存器)。SPI读取需先拉低片选(CS),发送寄存器地址,再读取数据,最后拉高CS。查找I2C设备,并调用。

xiaoheshang_123的博客 133

DDR5 JEDEC标准简析:一次读懂DDR5的核心规范!

JEDEC,全称是,中文名称是「电子元件工程联合委员会」,它是全球权威的存储接口标准制定机构。我们常见的 DDR2、DDR3、DDR4、DDR5 都是它搞出来的。📌 JEDEC 就像存储接口界的“裁判+编剧”——规定谁该怎么跑,怎么演,怎么配合。

weixin_43199439的博客 2612

多线程之GCD的简单使用

GCD为Grand Central Dispatch的缩写,是Apple开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器以及其他对称多处理系统,是一个在线程池模式的基础上执行的并行任务。   GCD是一个替代诸如NSThread等技术的很高效和强大的技术。GCD完全可以处理诸如数据锁定和资源泄漏等复杂的异步编程问题。GCD的工作原理是让一个程序,根据可用的处理资源,安排他

Enrica_Shi的博客 636

RK356X linux系统移植RTL8723BU模块遇到的坑

RK356X linux系统移植RTL8723BU模块遇到的坑

目前从事linux驱动开发,多交流多学习吧 961

iOS面试:4.多线程GCD

进程是指在系统中正在运行的一个应用程序。对于电脑而已,你打开一个软件,就相当于开启了一个进程。对于手机而已,你打开了一个APP,就相当于开启了一个进程。线程是进程的基本执行单位。一个进程中至少会有一条线程,当然也可能会有多条线程。比如你使用QQ音乐听歌,系统会创建一条线程去播放音乐。使用QQ音乐下载歌曲,系统会创建一条线程去下载歌曲。这两个操作是可以同时进行的,也就说一个进程中可以同时运行多条线程。

长沙火山 3072

adobe acrobat pro 2024出现THIS APP HAS BEEN DISABLED——下面是解决方法——w有效!

今天我来分享一个简单有效的解决方法,助你秒杀这个烦人的弹窗!找到名为AcroCEF.exe的文件,它位于AcroCEF_1文件夹下: C:\Program Files\Adobe\Acrobat DC\Acrobat\acrocef_1\AcroCEF.exe复制这个文件的完整路径!你将进入软件的安装目录,路径类似于:C:\Program Files\Adobe\Acrobat DC\Acrobat。新建一个规则:选择程序,点击浏览,粘贴刚刚复制的AcroCEF.exe路径,选择阻止连接。

qq_15963745的博客 1万+

【深度学习新浪潮】Token经济学深度解析:从AI“新智元”梗到产业核心,研究成果+标杆产品全拆解

在正式深入研究和产品分析前,必须先破除概念误区:行业内常说的Token经济学,并非单一概念,而是分为AI词元Token经济学和Web3通证Token经济学两大核心分支,二者底层逻辑、应用场景天差地别,也是大众最容易混淆的点。Token是AI时代的新大宗商品:黄仁勋将Token类比为工业时代的电力、石油,是AI时代的核心生产资料与基础计价单位,不再是单纯的技术单元,而是具备标准化、可计量、可交易、可分层的数字商品,其价值由算力消耗、推理效率、实际应用价值共同决定,而非虚拟炒作。Token五层定价模型。

专注:太空算力、AI infra、异构调度、大模型成本工程 696

一文看懂iOS多线程并发(NSThread、GCD、NSOperation&&NSOperationQueue)

一万一千字带你进入iOS多线程并发的世界!

ScheenDuan的博客 2456

深度学习工具包 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")

iOS - 多线程-GCD

GNUstep是GNU计划的项目之一,它将Cocoa的OC库重新开源实现了一遍。虽然GNUstep不是苹果官方源码,但还是具有一定的参考价值。队列(Concurrent Dispatch Queue)看似是在没有延迟的情况下执行,实际上因为该方法是基于。队列(Serial Dispatch Queue)添加一个定时器,但是因为此时我们是在。这时候都有打印,只不过打印顺序。主要影响:能不能开启新的线程。主要影响:任务的执行方式。上面的例子中,主要是考察。,这次打印顺序是正常的。

sharp521的博客 1232

Devexpress16.2.6破解工具

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

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

iOS——【GCD】

GCD指的是Grand Central Dispatch,它是苹果公司开发的一套多线程编程技术。GCD提供了一种简单而有效的方式来管理应用程序中的并发任务。它通过将任务提交到适当的队列(串行队列或并发队列)来管理并发执行的任务,从而帮助开发者更轻松地实现并发编程,提高应用程序的性能和响应速度。上面的就是在后合线程中执行长时间处理,处理结束时,主线程使用该处理结果的源代码。这样,dispatch_async (queue, ^{ 这仅有 一行的代码表示让处理在后台线程中执行。

m0_73348697的博客 1922

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

【iOS】GCD详解

详解GCD

cheng_lin0201的博客 2063

iOS—GCD详解

文章目录多线程编程进程线程线程与进程的关系多线程编程多线程编程的问题GCD什么是GCDGCD任务和队列GCD的使用步骤队列的创建队列的获取任务的创建方法任务与队列不同组合方式的区别同步执行 + 并发队列异步执行 + 并发队列同步执行 + 串行队列异步执行 + 串行队列同步执行 + 主队列在主线程中调用 同步执行+主队列在其他线程中调用 同步执行+主队列异步执行 + 主队列GCD其他方法GCD栅栏方法:dispatch_barrier_asyncGCD延时执行方法:dispatch_afterGCD 一次性代

qq_45836906的博客 6625

iOS多线程编程及GCD简介

程序APP进程、线程、多线程 1.程序是计算机(电脑,智能手机,机器人等有操作系统的智能新生物)指令的集合,以文件形式存储在磁盘上。 2.进程是一个正在运行的程序实例,是一个程序在其自身的地址空间中的一次执行活动。 3.进程由内核对象和地址空间组成。 4.线程由内核对象和线程栈组成,它是进程运行过程中的某个时间片,多核CUP时,线程就实现了同时运行。 iOS提供四种多线程编程技术 ...

zhuxincheng_1218的专栏 1007

iOS多线程编程——浅谈GCD

GCD对于iOS开发者来说肯定不陌生,他和NSThread,NSOperation一起作为iOS开发中主要的三种多线程实现方法,而GCD是最最底层的,所以对于作为一个iOSer,GCD是必须掌握的。

zkh90644的博客 2894

iOS中的多线程与GCD队列关系

文章目录1、iOS中的常见多线程方案2、GCD与队列2.1、常用函数2.2、queue队列2.3、同步、异步、并发、串行2.4、各种队列的执行效果2.5、队列组的使用3、问答拓展 1、iOS中的常见多线程方案 2、GCD与队列 2.1、常用函数 GCD中有2个用来执行任务的函数 1、用同步的方式执行任务 /** * @param: queue:队列 * @param: block:任务 */ dispatch_sync(dispatch_queue_t queue, dispatch_block_t b.

chenzimin_blog 859

iOS多线程技术3 - GCD的详细用法

多线程的相关概念 工欲善其事,必先利其器,在进入 GCD 学习之前,我们有必要先了解一下多线程的一些概念。 进程:进程是程序在计算机上的一次执行活动。例如打开一个 app,就开启了一个进程,一个进程可以并发多个线程。 线程:线程就是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一个线程同一时间只能执行一个任务,平时我们所说的多任务并发实际上是多个线程并发去...

毛毛虫 1859

iOS多线程GCD

Grand Central Dispatch (GCD)是Apple开发的一个多核编程的解决方法。 dispatch queue分成以下三种: 1)运行在主线程的Main queue,通过dispatch_get_main_queue获取。 /*! * @function dispatch_get_main_queue * * @abstract * Returns the defa

afdl9999的专栏 3万+
上一篇: iOS RunLoop 理解
下一篇: iOS 单例(singleton,GCD,@synchronize)
jeverson.jee
博客等级 码龄11年 66粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值