iOS多线程

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

  • Pthreads
  • NSThread
  • GCD
  • NSOperation & NSOperationQueue

 

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

 

 

1Pthreads

POSIX线程

 

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

 

2NSThread

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

// 创建

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

// 启动

  [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:^{

 

}];

 

 

原文地址:https://www.cnblogs.com/tiechui/p/8288591.html