iOS多线程

2019年11月08日 阅读数:22
这篇文章主要向大家介绍iOS多线程,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

https://www.jianshu.com/p/0b0d9b1f1f19web

  • Pthreads
  • NSThread
  • GCD
  • NSOperation & NSOperationQueue

 

线程同步、 延时执行、 单例模式多线程

 

 

1Pthreads并发

POSIX线程异步

 

pthread_create(&thread, NULL, start, NULL);async

 

2NSThreadspa

1—先建立线程类,再启动线程

// 建立3d

  NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:nil];orm

// 启动队列

  [thread start];

 

2-建立并自动启动

  [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil];

 

 

3-NSObject 的方法建立并自动启动

[self performSelectorInBackground:@selector(run:) withObject:nil];

 

 

 

3GCD

任务  队列

 

同步(sync  异步(async

会不会阻塞当前线程,直到 Block 中的任务执行完毕!

 

 

串行队列  并行队列

 

异步:

串行队列:开多个线程,单个执行

并行队列:开不少线程,一块儿执行

 

 

主队列-串行

  dispatch_queue_t queue = dispatch_get_main_queue();

 

本身建立的队列

DISPATCH_QUEUE_SERIAL  NULL 表示建立串行队列。传入 DISPATCH_QUEUE_CONCURRENT 表示建立并行队列。

 

全局并行队列

  dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

 

 

同步任务

dispatch_sync

 

 

异步任务

dispatch_async

 

 

 

 

队列组

dispatch_group_t group = dispatch_group_create();

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_async(group, queue, ^{

dispatch_group_async(group, dispatch_get_main_queue(), ^{

dispatch_group_async(group, queue, ^{

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

 

??阑珊用法:dispatch_barrier_async

 

 

4NSOperationNSOperationQueue

NSInvocationOperation  NSBlockOperation   + start 

 

 

addExecutionBlock

Operation 添加多个执行 Block,任务 会并发执行,在主线程和其它的多个线程 执行这些任务

 

自定义Operation

main() 

 

 

 

 

NSOperationQueue

主队列

NSOperationQueue *queue = [NSOperationQueue mainQueue];

 

其余队列

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[operation addExecutionBlock:

[queue addOperation:operation];

 

 

 

maxConcurrentOperationCount = 1 串行队列

 

 

 

添加依赖

 

 

[operation2 addDependency:operation1];      //任务二依赖任务一

[operation3 addDependency:operation2];      //任务三依赖任务二

[queue addOperations:@[operation3, operation2, operation1] waitUntilFinished:NO];

removeDependency 来解除依赖关系。

 

 

 

 

线程同步

互斥锁 

@synchronized(self)

/须要执行的代码块

NSLock

NSRecursiveLock  嵌套锁

 

同步执行

1dispatch_sync

2

[queue addOperation:operation];

 

[operation waitUntilFinished];

 

 

延迟执行

1-

[self performSelector:@selector(run:) withObject:@"abc" afterDelay:3];

2-

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), queue, ^{

3-

  • [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo:@"abc" repeats:NO];

 

 

从其余线程回到主线程的方法

1[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:NO];

2GCD

//Objective-C

dispatch_async(dispatch_get_main_queue(), ^{

 

});

3NSOperationQueue

//Objective-C

[[NSOperationQueue mainQueue] addOperationWithBlock:^{

 

}];