Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dispatch_async 阻塞的是当前所在队列 还是队列中线程? #31

Closed
webMing opened this issue Jan 7, 2019 · 5 comments
Closed

Comments

@webMing
Copy link

webMing commented Jan 7, 2019

###并发编程案例4中代码: 点击查看代码

NSLog(@"1"); // 任务1
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    NSLog(@"2"); // 任务2
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"3"); // 任务3
    });
    NSLog(@"4"); // 任务4
});
NSLog(@"5"); // 任务5

案例的分析结果是: 1最先执行;2和5顺序不一定;4一定在3后面;
我的疑问是如果说4一定在3后面,那么是否能够说明 dispatch_async 阻塞的是当前所在队列;内部的dispatch_sync在阻塞的并发队列的情况下才有可能4一定在3后面,因为任务2,任务4,和同步派发(dispatch_sync)可能分配到不同线程中执行;如果阻塞的是线程,那么任务3和任务4执行的顺序就不一定了. @skyline75489

###这个问题也可以这样描述:

为什么在global中 任务2, dispath_asyn, 任务4,不是放在不同不同的线程中并行执行的?.

Tanks in advance.

@skyline75489
Copy link
Contributor

你的问题表达不是很清晰。中间那个 dispatch_sync 会导致 “3” 执行完之后再执行 “4”。

@webMing
Copy link
Author

webMing commented Jan 8, 2019

你的问题表达不是很清晰。中间那个 dispatch_sync 会导致 “3” 执行完之后再执行 “4”。

👌,我的疑问是 dispatch_sync 阻塞的是global_queue 还是global_queue 中被派发执行任务的线程(现在已经有答案了:阻塞的是线程)?

个人觉得上图中很容易造成 dispatch_sync 阻塞的是queue,而不是queue中的线程.下面我做了补充.
途中省略的文字和上面箭头文字一样哈.

下面是我找到有助于理解的解释:
GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Work submitted to dispatch queues are executed on a pool of threads fully managed by the system. No guarantee is made as to the thread on which a task executes.see more

@skyline75489
Copy link
Contributor

线程。block 里面的代码已经开始执行了,就和 queue 的阻塞与否无关了。queue 的阻塞(你想表达的应该是串行和并行的区别)与否是 queue 本身的性质。

@webMing
Copy link
Author

webMing commented Jan 8, 2019

线程。block 里面的代码已经开始执行了,就和 queue 的阻塞与否无关了。queue 的阻塞(你想表达的应该是串行和并行的区别)与否是 queue 本身的性质。

谢谢.

@gongdeyin
Copy link

dispatch_async 会异步执行,不会阻塞当前call thread,里面的block会在一个thread上跑,thread是主线程还是非主线程取决你的queue;
dispatch_sync 会同步执行,会阻塞当前call thread,里面block会搭载在当前线程上跑,thread是主线程还是非主线程取决你的queue;

block相当于是货车拉的货物,线程就是车,空车是不准发车,只有有货才能发,所以,这里如果说有阻塞,是阻塞在queue里面的block(货物),货物才决定执行(发车)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants