GCD中线程和队列之间的关系是什么? [英] What's the relationship between thread and queue in GCD?

查看:256
本文介绍了GCD中线程和队列之间的关系是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 一个线程只包含一个队列吗?

  2. 如果我将一个块异步调度到globalQueue,它是否可以在主线程上运行?

  3. 什么样的情况会导致 dispatch_sync 死锁?

  1. does one thread only contain one queue?
  2. if I dispatch a block asynchronously to globalQueue ,can it run on main thread by any chance?
  3. what kind of situation will cause dispatch_sync to dead lock?


推荐答案

1。一个线程只包含一个队列吗?

1. Does one thread only contain one queue?

这种关系是一种方式。串行队列可以保存一个线程来执行分派给它的块,但是线程不知道队列。好吧,主线程是特殊的,它知道主队列。

The relationship is one way. Serial queue may hold a thread to execute the block dispatched to it, but thread doesn't know a queue. Well, main thread is special, it knows the main queue.

我的猜测

My guess

调度队列没有指示它将运行块或函数的线程,我认为调度队列管理包含许多线程的线程池,它将在调度块时获取一个空闲线程。所以一个线程可以在一段时间内用于许多调度队列。

Dispatch queue doesn't indicate which thread it will run block or function on, I think dispatch queue manages a thread pool which contains many thread, it will fetch one idle thread when a block is dispatched. So one thread may work for many dispatch queue in a period time.

但是有人认为是肯定的:当你将一个块发送到队列时,这个块的线程正在为一个确定的调度队列运行,您可以使用 dispatch_get_current_queue 来获取它。

But one think is for sure: when you dispatch a block to a queue, the thread which this block is running on works for one determined dispatch queue, you can get it using dispatch_get_current_queue.

2。如果我将一个块异步调度到globalQueue,它是否可以在主线程上运行?

2. If I dispatch a block asynchronously to globalQueue ,can it run on main thread by any chance?

我认为它不会运行任何在主线程上阻塞到globalQueue,因为它无法评估块的执行时间,如果它是一个长时间的工作,它将阻塞主线程。

I think it won't run any block to globalQueue on main thread, because it can't evaluate the execution time of the block, if it is a long time job, it will block the main thread.

3。什么样的情况会导致dispatch_sync死锁?

3. what kind of situation will cause dispatch_sync to dead lock?

我引用并发编程指南中的段落


你永远不应该从在同一队列中执行的任务调用dispatch_sync或dispatch_sync_f函数
您计划
传递给该函数。这对于串行
队列尤其重要,这些队列可以保证死锁,但对于并发队列也应该避免

You should never call the dispatch_sync or dispatch_sync_f function from a task that is executing in the same queue that you are planning to pass to the function. This is particularly important for serial queues, which are guaranteed to deadlock, but should also be avoided for concurrent queues.

这篇关于GCD中线程和队列之间的关系是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆