总结ing
1,iOS的GCD中如何关闭或者杀死一个还没执行完的后台线程?
举例来说,我通过导航进入到了一个视图,这个视图加载的时候会新建一个线程在后台运行,假设这个线程需要从网络中读取许多数据,需要一定的时间,并且会在获取全部数据以后刷新UI界面(通过dispatch_async(dispatch_get_main_queue(), ^{...});),我可能在它还未运行完的时候通过导航返回到上一层视图,所以我想在我返回前杀死或者结束这个还未执行完的线程,应该怎么做? 还有,如果我放任这个线程,在我返回到上层视图的时候,本视图应该会被释放,那么线程中有关主线程中运行的代码会怎么办?
回答:GCD本身是没有提供这样的API的。想要实现这样的功能需要自己在代码里实现:
著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
作者:刘子洋
链接:https://www.zhihu.com/question/23919984/answer/26129416
来源:知乎 @interface Canceller
{
BOOL _shouldCancel;
}
- (void)setShouldCancel:(BOOL)shouldCancel;
- (BOOL)shouldCancel;
@end @implementation Canceller
- (void)setShouldCancel:(BOOL)shouldCancel {
_shouldCancel = shouldCancel;
}
- (BOOL)shouldCancel {
return _shouldCancel;
}
@end static void test(int a){
static Canceller * canceller = nil; if(q){
[canceller setShouldCancel:YES];
[canceller release];
dispatch_suspend(q);
dispatch_release(q);
q=nil;
}
canceller = [[Canceller alloc] init];
q=dispatch_get_global_queue(,);
dispatch_async(q,^ {
while(![canceller shouldCancel]){NSLog(@"query %d",a);sleep();}
}); }
2. Notification与多线程
前几天与同事讨论到Notification在多线程下的转发问题,所以就此整理一下。
先来看看官方的文档,是这样写的:
In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.
翻译过来是:
在多线程应用中,Notification在哪个线程中post,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。
也就是说,Notification的发送与接收处理都是在同一个线程中。为了说明这一点,我们先来看一个示例:
代码清单1:Notification的发送与处理
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"current thread = %@", [NSThread currentThread]);
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];
});
}
- (void)handleNotification:(NSNotification *)notification
{
NSLog(@"current thread = %@", [NSThread currentThread]);
NSLog(@"test notification");
}
@end
其输出结果如下:
2015-03-11 22:05:12.856 test[865:45102] current thread = {number = 1, name = main}
2015-03-11 22:05:12.857 test[865:45174] current thread = {number = 2, name = (null)}
2015-03-11 22:05:12.857 test[865:45174] test notification
可以看到,虽然我们在主线程中注册了通知的观察者,但在全局队列中post的Notification,并不是在主线程处理的。所以,这时候就需要注意,如果我们想在回调中处理与UI相关的操作,需要确保是在主线程中执行回调。
这时,就有一个问题了,如果我们的Notification是在二级线程中post的,如何能在主线程中对这个Notification进行处理呢?或者换个提法,如果我们希望一个Notification的post线程与转发线程不是同一个线程,应该怎么办呢?我们看看官方文档是怎么说的:
For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
这里讲到了“重定向”,就是我们在Notification所在的默认线程中捕获这些分发的通知,然后将其重定向到指定的线程中。
一种重定向的实现思路是自定义一个通知队列(注意,不是NSNotificationQueue对象,而是一个数组),让这个队列去维护那些我们需要重定向的Notification。我们仍然是像平常一样去注册一个通知的观察者,当Notification来了时,先看看post这个Notification的线程是不是我们所期望的线程,如果不是,则将这个Notification存储到我们的队列中,并发送一个信号(signal)到期望的线程中,来告诉这个线程需要处理一个Notification。指定的线程在收到信号后,将Notification从队列中移除,并进行处理。
官方文档已经给出了示例代码,在此借用一下,以测试实际结果:
代码清单2:在不同线程中post和转发一个Notification
@interface ViewController () @property (nonatomic) NSMutableArray *notifications; // 通知队列
@property (nonatomic) NSThread *notificationThread; // 期望线程
@property (nonatomic) NSLock *notificationLock; // 用于对通知队列加锁的锁对象,避免线程冲突
@property (nonatomic) NSMachPort *notificationPort; // 用于向期望线程发送信号的通信端口 @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; NSLog(@"current thread = %@", [NSThread currentThread]); // 初始化
self.notifications = [[NSMutableArray alloc] init];
self.notificationLock = [[NSLock alloc] init]; self.notificationThread = [NSThread currentThread];
self.notificationPort = [[NSMachPort alloc] init];
self.notificationPort.delegate = self; // 往当前线程的run loop添加端口源
// 当Mach消息到达而接收线程的run loop没有运行时,则内核会保存这条消息,直到下一次进入run loop
[[NSRunLoop currentRunLoop] addPort:self.notificationPort
forMode:(__bridge NSString *)kCFRunLoopCommonModes]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"TestNotification" object:nil]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil]; });
} - (void)handleMachMessage:(void *)msg { [self.notificationLock lock]; while ([self.notifications count]) {
NSNotification *notification = [self.notifications objectAtIndex:0];
[self.notifications removeObjectAtIndex:0];
[self.notificationLock unlock];
[self processNotification:notification];
[self.notificationLock lock];
}; [self.notificationLock unlock];
} - (void)processNotification:(NSNotification *)notification { if ([NSThread currentThread] != _notificationThread) {
// Forward the notification to the correct thread.
[self.notificationLock lock];
[self.notifications addObject:notification];
[self.notificationLock unlock];
[self.notificationPort sendBeforeDate:[NSDate date]
components:nil
from:nil
reserved:0];
}
else {
// Process the notification here;
NSLog(@"current thread = %@", [NSThread currentThread]);
NSLog(@"process notification");
}
} @end
运行后,其输出如下:
2015-03-11 23:38:31.637 test[1474:92483] current thread = {number = 1, name = main}
2015-03-11 23:38:31.663 test[1474:92483] current thread = {number = 1, name = main}
2015-03-11 23:38:31.663 test[1474:92483] process notification
可以看到,我们在全局dispatch队列中抛出的Notification,如愿地在主线程中接收到了。
这种实现方式的具体解析及其局限性大家可以参考官方文档Delivering Notifications To Particular Threads,在此不多做解释。当然,更好的方法可能是我们自己去子类化一个NSNotificationCenter,或者单独写一个类来处理这种转发。
NSNotificationCenter的线程安全性
苹果之所以采取通知中心在同一个线程中post和转发同一消息这一策略,应该是出于线程安全的角度来考量的。官方文档告诉我们,NSNotificationCenter是一个线程安全类,我们可以在多线程环境下使用同一个NSNotificationCenter对象而不需要加锁。原文在Threading Programming Guide中,具体如下:
The following classes and functions are generally considered to be thread-safe. You can use the same instance from multiple threads without first acquiring a lock. NSArray
...
NSNotification
NSNotificationCenter
...
我们可以在任何线程中添加/删除通知的观察者,也可以在任何线程中post一个通知。
NSNotificationCenter在线程安全性方面已经做了不少工作了,那是否意味着我们可以高枕无忧了呢?再回过头来看看第一个例子,我们稍微改造一下,一点一点来:
代码清单3:NSNotificationCenter的通用模式
@interface Observer : NSObject @end @implementation Observer - (instancetype)init
{
self = [super init]; if (self)
{
_poster = [[Poster alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil]
} return self;
} - (void)handleNotification:(NSNotification *)notification
{
NSLog(@"handle notification ");
} - (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
} @end // 其它地方
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
上面的代码就是我们通常所做的事情:添加一个通知监听者,定义一个回调,并在所属对象释放时移除监听者;然后在程序的某个地方post一个通知。简单明了,如果这一切都是发生在一个线程里面,或者至少dealloc方法是在-postNotificationName:的线程中运行的(注意:NSNotification的post和转发是同步的),那么都OK,没有线程安全问题。但如果dealloc方法和-postNotificationName:方法不在同一个线程中运行时,会出现什么问题呢?
我们再改造一下上面的代码:
代码清单4:NSNotificationCenter引发的线程安全问题
#pragma mark - Poster @interface Poster : NSObject @end @implementation Poster - (instancetype)init
{
self = [super init]; if (self)
{
[self performSelectorInBackground:@selector(postNotification) withObject:nil];
} return self;
} - (void)postNotification
{
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
} @end #pragma mark - Observer @interface Observer : NSObject
{
Poster *_poster;
} @property (nonatomic, assign) NSInteger i; @end @implementation Observer - (instancetype)init
{
self = [super init]; if (self)
{
_poster = [[Poster alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
} return self;
} - (void)handleNotification:(NSNotification *)notification
{
NSLog(@"handle notification begin");
sleep(1);
NSLog(@"handle notification end"); self.i = 10;
} - (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self]; NSLog(@"Observer dealloc");
} @end #pragma mark - ViewController @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; __autoreleasing Observer *observer = [[Observer alloc] init];
} @end
这段代码是在主线程添加了一个TEST_NOTIFICATION通知的监听者,并在主线程中将其移除,而我们的NSNotification是在后台线程中post的。在通知处理函数中,我们让回调所在的线程睡眠1秒钟,然后再去设置属性i值。这时会发生什么呢?我们先来看看输出结果:
2015-03-14 00:31:41.286 SKTest[932:88791] handle notification begin
2015-03-14 00:31:41.291 SKTest[932:88713] Observer dealloc
2015-03-14 00:31:42.361 SKTest[932:88791] handle notification end
(lldb) // 程序在self.i = 10处抛出了"Thread 6: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)"
经典的内存错误,程序崩溃了。其实从输出结果中,我们就可以看到到底是发生了什么事。我们简要描述一下:
当我们注册一个观察者是,通知中心会持有观察者的一个弱引用,来确保观察者是可用的。
主线程调用dealloc操作会让Observer对象的引用计数减为0,这时对象会被释放掉。
后台线程发送一个通知,如果此时Observer还未被释放,则会用其转出消息,并执行回调方法。而如果在回调执行的过程中对象被释放了,就会出现上面的问题。
当然,上面这个例子是故意而为之,但不排除在实际编码中会遇到类似的问题。虽然NSNotificationCenter是线程安全的,但并不意味着我们在使用时就可以保证线程安全的,如果稍不注意,还是会出现线程问题。
那我们该怎么做呢?这里有一些好的建议:
尽量在一个线程中处理通知相关的操作,大部分情况下,这样做都能确保通知的正常工作。不过,我们无法确定到底会在哪个线程中调用dealloc方法,所以这一点还是比较困难。
注册监听都时,使用基于block的API。这样我们在block还要继续调用self的属性或方法,就可以通过weak-strong的方式来处理。具体大家可以改造下上面的代码试试是什么效果。
使用带有安全生命周期的对象,这一点对象单例对象来说再合适不过了,在应用的整个生命周期都不会被释放。
使用代理。
小结
NSNotificationCenter虽然是线程安全的,但不要被这个事实所误导。在涉及到多线程时,我们还是需要多加小心,避免出现上面的线程问题。想进一步了解的话,可以查看Observers and Thread Safety。
总结ing的更多相关文章
- 《Android NFC 开发实战详解 》简介+源码+样章+勘误ING
<Android NFC 开发实战详解>简介+源码+样章+勘误ING SkySeraph Mar. 14th 2014 Email:skyseraph00@163.com 更多精彩请直接 ...
- 2106 Problem F Shuffling Along 中石油-未提交-->已提交
题目描述 Most of you have played card games (and if you haven’t, why not???) in which the deck of cards ...
- 数据爬取ing
ing import urllib for i in range(0,1,1): url='****/GetData?loginName=&userName=&beginDate=20 ...
- mac 开发必备软件(不断update ing...)
整理下mac环境下, 开发必备的一些软件吧, 由于不断要更新ing, 用到啥就写啥~球轻拍 1.host 绑定切换神器 a.gas mask : 只能切换单个自定义的host文件 b.ihosts(推 ...
- 适合入门自学服装裁剪滴书(更新ing)
[♣]适合入门自学服装裁剪滴书(更新ing) [♣]适合入门自学服装裁剪滴书(更新ing) 适合入门自学服装裁剪滴书(更新ing) 来自: 裁缝阿普(不为良匠,便为良医.) 2014-04-06 23 ...
- 8月30号周五香港接单ING~~化妆品只加10元!!!!!!
8月30号周五香港接单ING~~化妆品只加10元!!!!!! 8月30号周五香港接单ING~~化妆品只加10元!!!!!!
- Atitit.播放系统规划新版本 and 最近版本回顾 v3 pbf.doc 1 版本11 (ing)41.1 规划h5本地缓存系列 41.2 Android版本app41.3 双类别系统,
Atitit.播放系统规划新版本 and 最近版本回顾 v3 pbf.doc 1 版本11 (ing)4 1.1 规划h5本地缓存系列 4 1.2 Android版本app4 1.3 双类别系统, ...
- NOI备战总结ing……
持续做题ing…… 已完成: 树套树 点分治 博弈论 凸包 杜教筛 反演 FFT 数位DP DP专栏 网络流 数学专栏 正在进行中: waiting: SAM Kd-tree 矩阵树 分治 FWT B ...
- How to Pronounce the I in ING
How to Pronounce the I in ING Share Tweet Share Tagged With: ING Verbs The I in ING is the IH as in ...
- AC自动机(简单版)(施工ing)
声明 想看加强版的戳这里(施工ing,作者正努力中)~ 先贴题目吧哎~ AC自动机加强版 洛谷 P3796 题目: 洛谷 P3808 (数据范围困了我好久 TAT) 反正涉及字符串的算法都很玄学 ...
随机推荐
- git使用笔记-比较分支差异
比如我们有 2 个分支:master, dev,现在想查看这两个 branch 的区别,有以下几种方式: 1.查看 dev 有,而 master 中没有的: git log dev ^master 同 ...
- 服务间调用--feign跟ribbon
微服务一般来说当然是多服务多实例的,那么这些服务之间如何相互调用呢?spring cloud之前我们用dubbo,把服务开放出来,在xml配好后就可以像调用本地service一样调用其它模块的服务了: ...
- ubuntu使用ppa源安装最新版本的git
国内也有ubuntu镜像源.但是里面的git都是1.9版本.最新的已经是2.3了 1 首先使用将ppa源加入Ubuntu,交大家 sudo add-apt-repository ppa:pdoes/p ...
- jq案例中遇到的知识点总结(会飞的小鸟和三级联动)
1.会飞的小鸟 ,按键盘的上下左右键,小鸟会上下左右的飞 知识点:1.keyCode 键盘按键对应的数字 比如 左上右下键 对应 37 38 39 40: 2.小鸟的位置:var bBird=$(&q ...
- HTML--备忘点
1.文档内的链接
- 详解HBase架构原理
一.什么是HBase HBase是一个高可靠.高性能.面向列.可伸缩的分布式存储系统,利用HBase技术可在廉价的PC Server上搭建大规模结构化存储集群. H ...
- poj 3140 树形去边差异最小
http://poj.org/problem?id=3140 依然是差异最小问题,不过这次是去边.思路是这样的,先记录每个点的子节点个数,然后遍历每个边. 有两个问题要注意: abs可能会出编译适配问 ...
- git 获取领先落后的命令
git --git-dir=/data/usr/local/gerrit-site/git/aixuexi-admin.git rev-list --left-right --count master ...
- 启动selenium server
java -jar selenium-server-standalone-2.37.0.jar
- springboot:ajax跨域请求解决方案
Cors详细介绍请看阮一峰的跨域资源共享 CORS 详解:http://www.ruanyifeng.com/blog/2016/04/cors.html SpringBoot使用CROS解决跨域问题 ...