J-Q
J-Q

Reputation: 372

GCD dispatch_set_target_queue function's 1st parameter type

The function prototype is this:

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));

I am confused why below code could pass compiling???

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 

I don't see any field in dispatch_object_t Union is a dispatch_queue_t, so how can queueB argument cause no compile errors?

Also. I wonder what "struct dispatch_object_s *_do;" field is? What is "struct dispatch_queue_s *_dq;"?

Upvotes: 1

Views: 404

Answers (1)

das
das

Reputation: 3681

You can think of dispatch_object_t as the "base class" of all the dispatch object types.

In "plain" C this uses the transparent union GCC extension, which essentially allows all pointer types in the union to be treated interchangeably with the union type when used as a function argument.

the macro below the block you quoted from dispatch/object.h explains the connection with dispatch_queue_t:

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

and then later on in dispatch/queue.h

DISPATCH_DECL(dispatch_queue);

i.e. dispatch_queue_t matches the _dq member of the transparent union and hence is a valid type to pass to the dispatch_object_t argument of dispatch_set_target_queue.

FWIW in Objective-C and C++ the dispatch_object_t superclass relationship is expressed using the respective object type system, c.f. the other sections in the dispatch_object_t area of dispatch/object.h.

Upvotes: 2

Related Questions