GCD dispatch_set_target_queue函数的第一个参数类型

时间:2014-08-04 10:26:26

标签: multithreading objective-c-blocks grand-central-dispatch

函数原型是:

void dispatch_set_target_queue(
   dispatch_object_t object,
   dispatch_queue_t queue);

typedef union {
   struct dispatch_object_s *_do;
   struct dispatch_continuation_s *_dc;
   struct dispatch_queue_s *_dq;
   struct dispatch_queue_attr_s *_dqa;
   struct dispatch_group_s *_dg;
   struct dispatch_source_s *_ds;
   struct dispatch_source_attr_s *_dsa;
   struct dispatch_semaphore_s *_dsema;
   struct dispatch_data_s *_ddata;
   struct dispatch_io_s *_dchannel;
   struct dispatch_operation_s *_doperation;
   struct dispatch_fld_s *_dfld;
} dispatch_object_t __attribute__((transparent_union));

我很困惑为什么下面的代码可以通过编译???

dispatch_queue_t queueA = dispatch_queue_create("com.effectiveobjectivec.queueA", NULL);
dispatch_queue_t queueB = dispatch_queue_create("com.effectiveobjectivec.queueB", NULL);
dispatch_set_target_queue(queueB, queueA); // will set queueA as queueB's target 

我没有看到dispatch_object_t Union中的任何字段是dispatch_queue_t,那么queueB参数怎么会导致编译错误?

另外。我想知道" struct dispatch_object_s *_do;"场是?什么是" struct dispatch_queue_s *_dq;"?

1 个答案:

答案 0 :(得分:2)

您可以将dispatch_object_t视为所有调度对象类型的“基类”。

在“plain”C中,它使用transparent union GCC扩展,当用作函数参数时,它实质上允许联合中的所有指针类型与union类型互换。

你从dispatch / object.h引用的块下面的宏解释了与dispatch_queue_t的连接:

#define DISPATCH_DECL(name) typedef struct name##_s *name##_t

然后在dispatch / queue.h中

DISPATCH_DECL(dispatch_queue);

即。 dispatch_queue_t与透明联合的_dq成员匹配,因此是传递给dispatch_object_t的{​​{1}}参数的有效类型。

在Objective-C和C ++中的FWIW dispatch_set_target_queue超类关系用相应的对象类型系统表示,c.f。 dispatch / object.h的dispatch_object_t区域中的其他部分。