iOS开发-GCD常用函数和其他用法

BQ27220燃料计量芯片与Arduino库kode_bq27220实战指南 燃料计量(Fuel Gauge)是嵌入式电池管理系统的核心技术,通过电压、电流、温度多维建模实现荷电状态(SOC)与健康状态(SOH)的动态估算。其原理基于电化学阻抗补偿算法(如CEDV),区别于简单电压查表法,具备自学习与老化适应能力。该技术显著提升便携设备续航预测精度与低功耗可靠性,广泛应用于TWS耳机、可穿戴设备及医疗电子等场景。本文围绕TI BQ27220高精度燃料计量IC及其配套Arduino库kode_bq27220展开,覆盖硬件连接规范、I²C初始化要点、SOC/SOH实时读取、EDV阈值配置 阅读详情

今天给同学书写上文GCD(Grand Central Dispatch) 来实现多线程的技术常用的函数和一些用法那么废话不多说直接上代码~

//
//  ZZGCDViewController.m
//  8-多线程技术
//
//  Created by Jordan zhou on 2018/11/5.
//  Copyright © 2018年 Jordan zhou. All rights reserved.
//

#import "ZZGCDViewController.h"

@interface ZZGCDViewController ()
/** 图片1 */
@property (nonatomic, strong) UIImage *image1;
/** 图片2 */
@property (nonatomic, strong) UIImage *image2;
@end

@implementation ZZGCDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self barrier];
}

/**
 *  栅栏
 */
- (void)barrier
{
    dispatch_queue_t queue = dispatch_queue_create("12312312", 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]);
    });
}

/**
 *  延迟执行
 */
- (void)delay
{
    [self performSelector:@selector(onceToken) withObject:nil afterDelay:2.0f];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self onceToken];
    });
    
    [NSTimer scheduledTimerWithTimeInterval:2.0f repeats:NO block:^(NSTimer * _Nonnull timer) {
        [self onceToken];
    }];
    
    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(onceToken) userInfo:nil repeats:NO];
}

/**
 *  一次性
 */
- (void)onceToken
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"onceToken----run");
    });
}

/**
 * 快速迭代
 */
- (void)apply
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    NSString *from = @"/Users/zhouzhao/Desktop/From";
    NSString *to = @"/Users/zhouzhao/Desktop/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];
        
#warning - 有的主线程中进行有的则在子线程中进行
        NSLog(@"%@---%@", [NSThread currentThread], subpath);
    });
}

/**
 * 传统文件剪切
 */
- (void)moveFile
{
    NSString *from = @"/Users/zhouzhao/Desktop/From";
    NSString *to = @"/Users/zhouzhao/Desktop/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];
            
            NSLog(@"%@---%@", [NSThread currentThread], subpath);
        });
    }
}

/**
 *  队列组
 */
- (void)gcdGroup
{
    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];
    });
    
#pragma mark - dispatch_group_notify 会等上面的任务执行完然后再执行这里
    
    // 3.将图片1、图片2合成一张新的图片
    dispatch_group_notify(group, queue, ^{
        // 开启新的图层上下文
        UIGraphicsBeginImageContext(CGSizeMake(100, 100));
        
        // 绘制图片
        [self.image1 drawInRect:CGRectMake(0, 0, 50, 100)];
        [self.image2 drawInRect:CGRectMake(50, 0, 50, 100)];
        
        // 取得上下文中的图片
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        
        // 结束上下文
        UIGraphicsEndImageContext();
        
        // 回到主线程显示图片
        dispatch_sync(queue, ^{
            // 显示图片
        });
    });
}

/**
 *  gcd通过block和c语言实现s
 */
- (void)gcdC
{
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
//    dispatch_sync(<#dispatch_queue_t  _Nonnull queue#>, <#^(void)block#>)
    
//    dispatch_sync_f(<#dispatch_queue_t  _Nonnull queue#>, NULL, download)
}

void download(void *data)
{
    
}

/**
 *  gcd实现下载图片完成线程间的通信
 */
- (void)gcdDownload
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 图片的网络路径
        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];
        
        // 生成图片
        UIImage *image = [UIImage imageWithData:data];
        
        // 回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            // 设置图片
            
        });
    });
}

/**
 * 同步函数 + 主队列:
 */
- (void)syncMain
{
    NSLog(@"syncMain ----- begin");
    
    // 1.获得主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    // 2.将任务加入队列
    dispatch_sync(queue, ^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    });

#pragma mark - 会造成线程的堵塞 不会有log打印
    NSLog(@"syncMain ----- end");
}

/**
 * 异步函数 + 主队列:只在主线程中执行任务
 */
- (void)asyncMain
{
    // 1.获得主队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    // 2.将任务加入队列
    dispatch_async(queue, ^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    });
}

/**
 * 同步函数 + 串行队列:不会开启新的线程,在当前线程执行任务。任务是串行的,执行完一个任务,再执行下一个任务
 */
- (void)syncSerial
{
    // 1.创建串行队列
    dispatch_queue_t queue = dispatch_queue_create("jordan.zhou.com", DISPATCH_QUEUE_SERIAL);
    
    // 2.将任务加入队列
    dispatch_sync(queue, ^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    });
}

/**
 * 异步函数 + 串行队列:会开启新的线程,但是任务是串行的,执行完一个任务,再执行下一个任务
 */
- (void)asyncSerial
{
    // 1.创建串行队列
    dispatch_queue_t queue = dispatch_queue_create("jordan.zhou.com", DISPATCH_QUEUE_SERIAL);
    //    dispatch_queue_t queue = dispatch_queue_create("jordan.zhou.com", NULL);
    
    // 2.将任务加入队列
    dispatch_async(queue, ^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    });
}

/**
 *  同步函数 + 并发队列:不会开启新的线程
 */
- (void)syncConcurrent
{
    // 1.获取全局的并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 2.将任务加入队列
    dispatch_sync(queue, ^{
        NSLog(@"1-----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"2-----%@", [NSThread currentThread]);
    });
    
    dispatch_sync(queue, ^{
        NSLog(@"3-----%@", [NSThread currentThread]);
    });

#pragma mark - 在当前线程执行 最后打印log
    NSLog(@"syncConcurrent--------end");
}

/**
 *  异步函数 + 并发队列:可以同时开启多条线程
 */
- (void)asyncConcurrent
{
    // 1.0创建一个并发队列
    // label : 相当于队列的名字
//    dispatch_queue_t queue = dispatch_queue_create("jordan.zhou.queue", DISPATCH_QUEUE_CONCURRENT);
    
    // 1.1获取全局的并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 2.将任务加入队列
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 10; i++) {
            NSLog(@"1----%@",[NSThread currentThread]);
        }
    });
    
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 10; i++) {
            NSLog(@"2----%@",[NSThread currentThread]);
        }
    });
    
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 10; i++) {
            NSLog(@"3----%@",[NSThread currentThread]);
        }
    });
    
#pragma mark - 会先执行完下面的log然后再执行上面的任务
    NSLog(@"asyncConcurrent--------end");
}
@end

麒麟v10系统安装 阅读详情

相关推荐

DeepSeek+知网研学:三步搞定文献矩阵与对比分析(实战指南)

本文提供了一套高效实用的文献管理分析实战指南,详细介绍了如何结合DeepSeek大模型与知网研学平台,通过三个核心步骤快速完成文献梳理。该方法能自动提炼文献核心要素、生成结构化对比矩阵,并辅助发现研究空白,显著提升学术研究者的文献分析效率与深度。

weixin_29061509的博客 490

iOS多线程-GCD之常用函数

延迟执行任务函数dispatch_after(.....) -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"start"); //dispatch_after 是异步执行的 //队列只决定在哪个线程中执行任务 并不能决定执行时间 ...

weixin_30911809的博客 102

UVM环境复位--stop_sequences()

在UVM验证环境中, stop_sequences是一个用于强制终止所有正在运行的 Sequence 的方法,通常用于动态控制激励生成流程。1.通过uvm_config_db传递事件和严格的同步机制,此方案符适用于复杂复位场景和动态测试控制。组件耦合:Driver 和 Sequence 不再直接依赖env,通过标准接口通信。竞争条件:确保 Driver 完成清理后再终止 Sequence。代码健壮性:使用非阻塞操作和事件监听,避免死锁。

qq_42779035的博客 3014

iOS GCD常用函数总结

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33909059的博客 150

【UE5】虚幻引擎Gameplay框架

游戏实例(UGameInstance)会在引擎启动时实例化,并保持活跃直至引擎关闭。这是一种管理器类,在游戏中不存在实体,但会追踪数据和运行代码。在联网多人游戏中,游戏实例不会被复制,而是独立存在于服务器以及所有互联的客户端上。所有你希望在关卡加载间保持的内容都应存于游戏实例中。例如,游戏实例是管理游戏保存系统的到地方。游戏实例还可以充当任意数量的 游戏实例子系统 的管理器,这些子系统由游戏实例创建和销毁,并且与游戏实例本身具有相同的生命周期。在线子系统就属于这类子系统。

一个写程序的 1795

别再只跑Demo了!用MovieLens数据集完整复现一个电影推荐系统(Python/Pandas实战)

本文详细介绍了如何利用MovieLens数据集从零构建一个完整的电影推荐系统,涵盖数据清洗、特征工程、推荐算法实现(协同过滤和矩阵分解)以及Web服务部署的全流程。通过Python和Pandas实战,读者可以掌握推荐系统的核心技术和生产环境部署技巧,不再局限于简单的Demo运行。

weixin_29062865的博客 149

GCD常用函数总结

GCD提供两种Dispatch Queue, 分别为Concurrent Dispatch Queue 和 Serial Dispatch Queue. Serial Dispatch Queue 使用一个thread。 Concurrent Dispatch Queue 使用多个thread。 获取Dispatch Queue:

1218

SAP CKMLCP 月结7大常见报错:从“未找到成本核算运行”到“物料占用”的完整解决方案

本文深入解析SAP CKMLCP月结过程中的7大常见报错,从权限问题到数据一致性错误,提供系统化的解决方案。重点解决'未找到成本核算运行'和'物料占用'等典型问题,帮助财务人员高效完成成本核算月结,确保数据准确性。

weixin_30299709的博客 415

GCD常用函数

1. ios延迟执行的几种方法 [selfperformSelector:@selector(方法)withObject:nilafterDelay:2.0]; [NSTimerscheduledTimerWithTimeInterval:2.0target:selfselector:@selector(方法)userInfo:nilrepeats:NO

anspencer的博客 1192

STM32与HT7038的高精度电能计量系统设计与实现

本文详细介绍了基于STM32微控制器与HT7038三相电能计量芯片的高精度电能计量系统设计与实现。文章从项目选型出发,深入剖析了硬件电路设计、SPI驱动开发、芯片校准及系统集成等关键环节,为智能电表、能源监控等应用提供了高性价比且稳定的国产化解决方案。

pytorch8learner的博客 389

Windows 下 OpenClaw(小龙虾) 安装全记录:从零到一的保姆级图文教程(持续更新中)

本文主要介绍了Windows 下 OpenClaw 安装全记录:从零到一的保姆级图文教程,希望能对学习使用OpenClaw 的同学们有所帮助。 文章目录 1. 背景 2. 实战教程 2.1 步骤一 安装Node.js 2.2 步骤二:安装并配置OpenClaw 2.3 步骤三:配置模型 2.4 步骤四:对话 3. 后续使用步骤

weixin_43178406的博客 16万+

GCD常用函数说明

提交队列函数(即执行): dispatch_async(dispatch_queue_t queue, ^(void)block):异步执行队列 dispatch_sync(dispatch_queue_t queue, ^(void)block) :同步执行队列(主线程) 获取queue函数: dispatch_get_global_queue(long identi

hcy_12345的专栏 2151

【Python计量】linearmodels面板数据回归(一)

我们以伍德里奇《计量经济学导论现代方法》的”第14章高级面板数据方法“的案例14.1为例,使用jtrain中的数据来进行固定效应估计。

mfsdmlove的博客 9277

c语言__gcd函数用法,iOS开发-GCD常用函数和其他用法

今天给同学书写上文GCD(Grand Central Dispatch) 来实现多线程的技术常用的函数和一些用法那么废话不多说直接上代码~//// ZZGCDViewController.m// 8-多线程技术//// Created by Jordan zhou on 2018/11/5.// Copyright © 2018年 Jordan zhou. All rights reser...

weixin_36160225的博客 571

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

ios使用GCD实现多线程的简单介绍

简单介绍ios的GCD使用方法,以及示例代码和推荐链接

kyfxbl 1668

深度学习工具包 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面试:4.多线程GCD

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

长沙火山 3062

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

IOS之GCD基础

IOS之GCD基础 1.栅栏函数的使用 // // ViewController.m // 01-掌握-GCD栅栏函数 // // Created by 鲁军 on 2021/6/3. // #import "ViewController.h" @implementation ViewController - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //0.获取全局并发队列

A1521315qwss的博客 149

iOS 多线程编程<二、GCD基本用法>

一:在学习多线程之前首先区分几个容易混淆的概念 二:GCD的基本用法 // // ViewController.m // GCD // // Created by fe on 16/9/30. // Copyright © 2016年 fe. All rights reserved. // #import "ViewController.h" @interface View

ZhengYanFeng1989的博客 437

GCD

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"]; NSError * error; NSString * data =

wenluma的专栏 733

gcd

GCD 是c语言的框架,不需要手动管理内存   是一个面向任务   不是面向线程,不需要管理线程的生命周期   GCD 任务/队列 执行函数 任务:Block  任务都封闭在Block中。  —— 线程执行   队列:存放任务    FIFO (先进先出的原则)         GCD中的队列:                        

hml19902006的专栏 521

【IOS】GCD学习

笔者近期学习了GCD的使用,对于GCD的认识更加深刻,本篇博客对笔者的学习进行一个小小的总结

2301_79847748的博客 1449

iOS——GCD再学习

在异步方法内又同步执行了一个方法,又因为同步执行中的方法执行完成前会阻塞当前线程,因此任务3执行完成前会一直阻塞线程,但是这个同步方法是处于串行队列的,因此要执行任务3要等待任务4执行完,但是任务4又要等任务3执行完才能执行,因此发生了死锁,跟那个主队列+同步执行差不多。syncConcurrent任务在其他线程中执行到追加 任务 1 到主队列中,因为主队列现在没有正在执行的任务,所以,会直接执行主队列的 任务1,等 任务1 执行完毕,再接着执行 任务 2、任务 3。(异步执行 具备开启新线程的能力。

m0_73348697的博客 2243

【iOS】 GCD小结

GCD是iOS开发中非常重要的一个内容,笔者今天对于这部分内容做一个介绍,GCD(Grand Central Dispatch)是Apple开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器以及其他对称多处理系统。它是一个在线程池模式的基础上,执行的并发任务。线程池模式:线程池工作队列已经装满了,且在线程池中正在运行的线程数小于可最大线程数。

qq_73106050的博客 1578

iOS中GCD的使用

在iOS开发中,所有的UI操作都是在主线程中进行的,那么如果将把耗时操作也放在主线程中,就会造成页面卡顿的现象。因此我们应该将耗时操作放在子线程中执行,GCD是iOS多线程当中比较常用的方法,下面简单介绍一下GCD的使用。 一、GCD当中的基本概念 1.同步函数和异步函数 同步函数: 同步函数不具备开启新线程的能力 dispatch_sync(dispatch_queue_t _Nonnull...

cherry的博客 2487

【iOS】GCD学习

本博客撰写一下小蓝书的GCDGrand Central Dispatch(GCD)是异步执行任务的技术之一。一般将应用程序中记述的线程管理用的代码在系统级中实现。开发者只需要定义想执行的任务并追加到适当的Dispatch Queue中,GCD就能生成必要的线程并计划执行任务。由于线程管理是作为系统的一部分来实现的,因此可统一管理,也可执行任务,这样就比以前的线程更有效率。//让处理在后台线程中执行/**长时间处理*例如AR用画像识别*例如数据库访问*//*

weixin_72437555的博客 1314

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

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

毛毛虫 1859
上一篇: iOS开发-多线程GCD的介绍和使用
下一篇: iOS开发-单例(粒)模式的介绍和实战使用
ZZ_iOSDeveloper
博客等级 码龄11年 21粉丝 74原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值