How to share sequential send queues between classes?

I noticed that they do not return pointers on creation, but actual objects. Therefore, to get a pointer, I try to declare it as follows:

dispatch_queue_t* queue; *queue = dispatch_queue_create("double_buffer_protection_queue", DISPATCH_QUEUE_SERIAL); 

The C ++ programmer in me says that it should work, but it gives a BAD_ACCESS error, so I assume that I am approaching this incorrectly.

If I need a sequential queue that any object in my program can access, how can I do this? The code shown above is intended for use in the AppDelegate class.

+4
source share
2 answers

In Grand Central Dispatch, using real objects is the right way. For instance,

 class Manager { Manager() { m_queue = dispatch_queue_create("double_buffer_protection_queue", DISPATCH_QUEUE_SERIAL); m_worker = new Worker(m_queue); } ~Manager() { dispatch_release(m_queue); delete m_worker; } dispatch_queue_t m_queue; Worker *m_worker; } 

And then the other queue owner must save and release it himself as Objective-C objects.

 class Worker { Worker(dispatch_queue_t queue) // Worker(dispatch_queue_t &queue) /* reference might be ok. */ { m_queue = queue; dispatch_retain(m_queue); } ~Worker() { dispatch_release(m_queue); } dispatch_queue_t m_queue; } 
+1
source

From GCD Link : typedef struct dispatch_queue_s *dispatch_queue_t;

Maybe I bark the wrong tree, but my gut will tell me that a more idiomatic solution might be to use the dispatch_once function inside the class method to get a queue with which multiple instances of the class can send work (this is not C ++ but you get the main idea):

 + (dispatch_queue_t)sharedQueue { static dispatch_once_t pred; static dispatch_queue_t sharedDispatchQueue; dispatch_once(&pred, ^{ sharedDispatchQueue = dispatch_queue_create("theSharedQueue", NULL); }); return sharedDispatchQueue; } 

dispatch_once ensures that queues are created only once during the entire execution time, so you can safely and cheaply call [YourClass sharedQueue] as often as you need, wherever you need to be.

However, my gut would also tell me that queuing between classes / objects smells a bit bad. If you just want the application queue to send different jobs, will the global queue be enough? If you want to do intensive work with large collections of objects, I would instinctively set up a separate queue for them. Maybe there is a more elegant way to do what you want?

+4
source

All Articles