主线队列,并发队列,串行队列,同步异步等的关系
最近直播研究中,很多地方涉及到多线程的问题,这里统一复习一下。
#import "ViewController.h" @interface ViewController () @end @implementation ViewController #pragma mark --主队列 /** 主线程执行同步任务会死锁:同步任务在添加进线程后就要当即执行,但是当前主线程正在执行text1函数,text1函数执行完成需要等待每一个顺序语句完成。所以发生了相互等待产生了死锁。 */ void text1(); /** 主线成执行异步任务:不会开新的线程,会在主线程依次执行任务。主队列添加完成block以后直接返回,主队列是顺序添加的block,block按照fifo执行。 */ void text2(); #pragma mark --并发队列 /** 并发队列执行同步任务:不创建线程,有序的执行所有的任务。这些任务都是创建一个就立马执行,执行完才创建下一个。同步函数是不会添加线程的,并发队列与否,并不影响同步函数的创建,因为本身就不能多创建线程,也就不存在并发。 */ void text3(); /** 并发队列执行异步任务:创建新的线程,各个线程也是并发执行的。 */ void text4(); #pragma mark --串行队列 /** 串行队列执行同步任务:不会创建线程,顺序执行任务。block任务执行完成以后继续向下执行任务。 注意:主队列虽然也是串行队列,但是会发生死锁。具体原因我也不知道。。。。。。 */ void text5(); /** 串行队列执行异步任务(与主队列一样):不会开新的线程,block任务会在主线程依次执行任务。主队列添加完成block以后直接返回继续执行下面的任务,主队列是顺序添加的block,block按照fifo执行。 */ void text6(); - (void)viewDidLoad { [super viewDidLoad]; // text1(); // text2(); // text3(); // text4(); // text5(); // text6(); } void text6(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t serialQue = dispatch_queue_create("fusheng", DISPATCH_QUEUE_SERIAL); for (int i = 0; i<10; i++) { dispatch_async(serialQue, ^{ NSLog(@"%d---%@",i,[NSThread currentThread]); }); } NSLog(@"end---%@",[NSThread currentThread]); } void text5(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t serialtQue = dispatch_queue_create("fusheng", DISPATCH_QUEUE_SERIAL); for (int i = 0; i<10; i++) { dispatch_sync(serialtQue, ^{ NSLog(@"%d---%@",i,[NSThread currentThread]); }); } NSLog(@"end---%@",[NSThread currentThread]); } void text4(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t concurrentQue = dispatch_queue_create("fusheng", DISPATCH_QUEUE_CONCURRENT); for (int i = 0; i<10; i++) { dispatch_async(concurrentQue, ^{ NSLog(@"%d---%@",i,[NSThread currentThread]); }); } NSLog(@"end---%@",[NSThread currentThread]); } void text3(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t concurrentQue = dispatch_queue_create("fusheng", DISPATCH_QUEUE_CONCURRENT); for (int i = 0; i<10; i++) { dispatch_sync(concurrentQue, ^{ NSLog(@"%d---%@",i,[NSThread currentThread]); }); } NSLog(@"end---%@",[NSThread currentThread]); } void text2(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t mainQue = dispatch_get_main_queue(); for (int i = 0; i<10; i++) { dispatch_async(mainQue, ^{ NSLog(@"%d---%@",i,[NSThread currentThread]); }); } NSLog(@"end---%@",[NSThread currentThread]); } void text1(){ NSLog(@"start---%@",[NSThread currentThread]); dispatch_queue_t mainQue = dispatch_get_main_queue(); dispatch_sync(mainQue, ^{ printf("2222 "); }); NSLog(@"end---%@",[NSThread currentThread]); } @end