Kumar Saurav
Kumar Saurav

Reputation: 43

Are dispatch_get_specific() & dispatch_queue_set_specific() thread safe?

I am trying to use dispatch_queue_set_specific() and dispatch_get_specific() in combination in method to check if the current queue is same as the target queue. But since this method can be called from multiple threads, I need to ensure thread safety. So, my question is are these methods thread safe. If not, how can I ensure thread safety here?

I am setting a data using dispatch_queue_set_specific() on the target queue and using dispatch_get_specific() to compare the data on current queue, if they are same I am on the same queue.

static inline (BOOL)is_current_queue(dispatch_queue_t queue) {
int key, data;
dispatch_queue_set_specific(queue, &key, &data, nil);
if (dispatch_get_specific(&key) == &data) {
return YES;
}
return NO;
}

Upvotes: 4

Views: 298

Answers (1)

CRD
CRD

Reputation: 53000

Are dispatch_get_specific() & dispatch_queue_set_specific() thread safe?

It would seem likely for routines in a concurrency library but the documentation isn't explicit on the point – just be thankful Apple actually provide any documentation at all, most if it is now relegated to their "documentation archive" ;-(

Fortunately for you libdispatch is open source and a check of the source confirms that they are – they lock around the critical parts.

HTH

BTW lines 4-8 of your code snippet are better written:

return dispatch_get_specific(&key) == &data;

Upvotes: 2

Related Questions