C++ 线程(串行 并行 同步 异步)详解
看了很多关于这类的文章,一直没有总结。不总结的话就会一直糊里糊涂,以下描述都是自己理解的非官方语言,不一定严谨,可当作参考。
首先,进程可理解成一个可执行文件的执行过程。在ios app上的话我们可以理解为我们的app的.ipa文件执行过程也即app运行过程。杀掉app进程就杀掉了这个app在系统里运行所占的内存。
线程:线程是进程的最小单位。一个进程里至少有一个主线程。就是那个main thread。非常简单的app可能只需要一个主线程即UI线程。当然大部分还是会有一些子线程的,比如如果你用了AFNetWorking,你的请求都是开辟了子线程。
关于串行,并行,同步,异步,我还是以下面代码的方式做个说明。
首先button点击事件运行在主线程里,先是在主线程里做了打印了一句话,然后创建了一个串行或者并行的队列,之后连续创建了3个同步或者异步的block任务放入此队列中,最后再在主线程里打印一句话。
- (IBAction)serialSync:(id)sender { NSLog(@"start log in main thread"]); dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL); for (NSInteger n = 0; n < 3; n++) { dispatch_sync(myQueue, ^{ for (NSInteger i = 0; i < 500000000; i++) { if (i == 0) { NSLog(@"串行同步任务%ld -> 开始%@",n,[NSThread currentThread]); } if (i == 499999999) { NSLog(@"串行同步任务%ld -> 完成",(long)n); } } }); } NSLog(@"阻塞我没有?当前线程%@",[NSThread currentThread]);}- (IBAction)serialAsync:(id)sender { NSLog(@"start log in main thread"]); dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);//创建一个串行队列 for (NSInteger n = 0; n < 3; n++) { dispatch_async(myQueue, ^{ for (NSInteger i = 0; i < 500000000; i++) { if (i == 0) { NSLog(@"串行异步任务%ld -> 开始%@",n,[NSThread currentThread]); } if (i == 499999999) { NSLog(@"串行异步任务%ld -> 完成",(long)n); } } }); } NSLog(@"阻塞我没有?当前线程%@",[NSThread currentThread]);}- (IBAction)concurrentSync:(id)sender { NSLog(@"start log in main thread"]); dispatch_queue_t myQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT); for (NSInteger n = 0; n < 3; n++) { dispatch_sync(myQueue, ^{ for (NSInteger i = 0; i < 500000000; i++) { if (i == 0) { NSLog(@"并行同步任务%ld -> 开始%@",(long)n,[NSThread currentThread]); } if (i == 499999999) { NSLog(@"并行同步任务%ld -> 完成",(long)n); } } }); } NSLog(@"阻塞我没有?当前线程%@",[NSThread currentThread]);}- (IBAction)concurrentAsync:(id)sender { NSLog(@"start log in main thread"]); dispatch_queue_t myQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT); for (NSInteger n = 0; n < 3; n++) { dispatch_async(myQueue, ^{ for (NSInteger i = 0; i < 500000000; i++) { if (i == 0) { NSLog(@"并行异步任务%ld -> 开始%@",n,[NSThread currentThread]); } if (i == 499999999) { NSLog(@"并行异步任务%ld -> 完成",(long)n); } } }); } NSLog(@"阻塞我没有?当前线程%@",[NSThread currentThread]);}
最后的结果如图: