创build具有相同名称的串行队列的两个对象共享同一个队列

不确定的行为,因为我怀疑我正在陷入僵局,

我有一个类与多个对象 – 每个对象创build一个具有相同名称的队列。 我不确定GCD是否在对象之间重复使用相同的队列,或者它们是否共享相同的名称。

例如

@interface MyClass -(void)doSomeWork @property (nonatomic,strong) dispatch_queue_t myQueue; @end @implementation MyClass -(id)init { self = [super init]; self.myQueue = dispatch_queue_create("MyQueue",DISPATCH_QUEUE_SERIAL); return self; } -(void)doSomeWork { dispatch_async(self.myQueue,^{ // some long running work }); } @end @interface SomeClassWhichCreatesALotOfObjects @end @implementation SomeClassWhichCreatesALotOfObjects -(void)someMethod { for(int i = 0; i < 10000; i++) { MyClass *object = [MyClass new]; [object doSomeWork]; // are these running in serial to each other or are each offset to the queue their object has created? Can't understand from the debugger } } @end 

正如苹果的文档所述,标签是:

附加到队列中的string标签,以便在debugging工具(如Instruments)中唯一标识它…

它被用来作为暗示,仅此而已。

编辑

这是您想要使用共享队列的代码。

 + (dispatch_queue_t)sharedQueue { static dispatch_queue_t sharedQueue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedQueue = dispatch_queue_create("MyQueue", NULL); }); return sharedQueue; } 

dispatch_queue_create正是名字所暗示的,它创build了一个调度队列。 你给它的标签不需要是唯一的,它只是用于debugging目的。