iOS 多線程GCD的基本使用,ios多線程gcd
《iOS多線程簡介》中提到:GCD中有2個核心概念:1、任務(執行什麼操作)2、隊列(用來存放任務)
那麼多線程GCD的基本使用有哪些呢?
可以分以下多種情況:
1、非同步函數 + 並發隊列
/** * 非同步函數 + 並發隊列:可以同時開啟多條線程 */- (void)asyncConcurrent{ // 1.建立一個並發隊列 // dispatch_queue_create(const char *label, dispatch_queue_attr_t attr); // label : 相當於隊列的名字 // dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_CONCURRENT); // 1.獲得全域的並發隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2.將任務排入佇列 dispatch_async(queue, ^{ for (NSInteger i = 0; i<3; i++) { NSLog(@"this is first %@",[NSThread currentThread]); } }); dispatch_async(queue, ^{ for (NSInteger i = 0; i<3; i++) { NSLog(@"this is second %@",[NSThread currentThread]); } }); dispatch_async(queue, ^{ for (NSInteger i = 0; i<3; i++) { NSLog(@"this is third %@",[NSThread currentThread]); } }); }
2、同步函數 + 並發隊列
/** * 同步函數 + 並發隊列:不會開啟新的線程 */- (void)syncConcurrent{ // 1.獲得全域的並發隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2.將任務排入佇列 dispatch_sync(queue, ^{ NSLog(@"this is first %@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"this is second %@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"this is third %@",[NSThread currentThread]); }); }
3、非同步函數 + 串列隊列
/** * 非同步函數 + 串列隊列:會開啟新的線程,但是任務是串列的,執行完一個任務,再執行下一個任務 */- (void)asyncSerial{ // 1.建立串列隊列 dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_SERIAL); // dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", NULL); // 2.將任務排入佇列 dispatch_async(queue, ^{ NSLog(@"this is first %@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"this is second %@",[NSThread currentThread]); }); dispatch_async(queue, ^{ NSLog(@"this is third %@",[NSThread currentThread]); });}
4、同步函數 + 串列隊列
/** * 同步函數 + 串列隊列:不會開啟新的線程,在當前線程執行任務。任務是串列的,執行完一個任務,再執行下一個任務 */- (void)syncSerial{ // 1.建立串列隊列 dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_SERIAL); // 2.將任務排入佇列 dispatch_sync(queue, ^{ NSLog(@"this is first %@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"this is second %@",[NSThread currentThread]); }); dispatch_sync(queue, ^{ NSLog(@"this is third %@",[NSThread currentThread]); });}
5、非同步函數 + 主隊列
// * 非同步函數 + 主隊列:只在主線程中執行任務- (void)asyncMain{ // 1.獲得主隊列 dispatch_queue_t queue = dispatch_get_main_queue(); // 2.將任務排入佇列 dispatch_async(queue, ^{ NSLog(@"this is first %@",[NSThread currentThread]); NSLog(@"this is second %@",[NSThread currentThread]); NSLog(@"this is third %@",[NSThread currentThread]); });}
6、同步函數 + 主隊列
// * 同步函數 + 主隊列:- (void)syncMain{ NSLog(@"begin"); // 1.獲得主隊列 dispatch_queue_t queue = dispatch_get_main_queue(); // 2.將任務排入佇列 dispatch_sync(queue, ^{ NSLog(@"this is %@",[NSThread currentThread]); }); NSLog(@"end");}
造成“相互等待的死結”