How to use dispatch_queue_set_specific() and dispatch_get_specific()

前端 未结 2 1819
情话喂你
情话喂你 2020-12-14 05:02

I\'m having a hard time finding good examples on how to use these functions.

static void * kQueue1Key = \"key1\";
static void * kQueue2Key = \"key2\";

disp         


        
相关标签:
2条回答
  • 2020-12-14 05:08

    Oh here, it popped into my head why you're getting what you're getting. Notes in line:

    dispatch_sync(queue1, ^{
    

    When you get to this point, the "current queue" is queue1

        if(dispatch_get_specific(kQueue1Key))
    

    You're asking the current queue for the value it has for kQueue1Key, you set that earlier, so it gives it back to you.

        {
            NSLog(@"I'm expecting this line to run (A)");
    
            dispatch_sync(queue2, ^{
    

    When you get to this point, the "current queue" is now queue2

                NSLog(@"I'm expecting this line to run (B)");
    
                if(dispatch_get_specific(kQueue2Key))
    

    You're asking the current queue for the value it has for kQueue2Key, you set that earlier, so it gives it back to you.

                {
    
                    if(dispatch_get_specific(kQueue1Key))
    

    You're now asking the current queue for the value it has for kQueue1Key. Since the current queue is queue2 and you never set a value with kQueue1Key on queue2 you get back NULL.

                    {
                        NSLog(@"I'm expecting this line to run (C)");
                    }
                    else
                    {
                        [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
                    }
    

    The misunderstanding here is that dispatch_get_specific doesn't traverse the stack of nested queues, it traverses the queue targeting lineage. For instance, if you did this instead,

    static void * kQueue1Key = (void*)"key1";
    static void * kQueue2Key = (void*)"key2";
    
    dispatch_queue_t queue1 = dispatch_queue_create("com.company.queue1", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t queue2 = dispatch_queue_create("com.company.queue2", DISPATCH_QUEUE_SERIAL);
    
    dispatch_queue_set_specific(queue1, kQueue1Key, (void *)kQueue1Key, NULL);
    dispatch_queue_set_specific(queue2, kQueue2Key, (void *)kQueue2Key, NULL);
    
    // Set Queue2 to target Queue1
    dispatch_set_target_queue(queue2, queue1);
    
    dispatch_sync(queue2, ^{
    
        if(dispatch_get_specific(kQueue1Key))
        {
            NSLog(@"I'm expecting this line to run (A)");
        }
        else
        {
            [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
        }
    
        if(dispatch_get_specific(kQueue2Key))
        {
            NSLog(@"I'm expecting this line to run (B)");
        }
        else
        {
            [NSException raise:NSInternalInconsistencyException format:@"Should not end up here (C)"];
        }
    });
    

    ...the targeting relationship is the one that gets traversed, not the stack relationship. It would be nice if there were something that traversed the stack relationship, but I'm not aware of anything (that you wouldn't have to implement yourself).

    0 讨论(0)
  • 2020-12-14 05:19

    As mentioned in my comment, recursive locking using dispatch_sync is, in the general case, not possible due to the possibility of non-default queue targeting. For what it's worth, given/assuming default queue targeting, here is one possible approach:

    #import <unordered_set>
    #import <pthread.h>
    
    static dispatch_once_t recursiveLockWithDispatchQueueTLSKeyOnceToken;
    static pthread_key_t recursiveLockWithDispatchQueueTLSKey;
    typedef std::unordered_multiset<const void*> RecursiveLockQueueBag;
    
    static void freeRecursiveLockWithDispatchQueueTLSValue(void* tlsValue)
    {
        RecursiveLockQueueBag* ms = reinterpret_cast<RecursiveLockQueueBag*>(tlsValue);
        if (ms) delete ms;
    }
    
    static inline BOOL queueStackCheck(dispatch_queue_t q, BOOL checkAndPushNotPop) // If yes, check and push if not on. If no, pop.
    {
        dispatch_once(&recursiveLockWithDispatchQueueTLSKeyOnceToken, ^{
            pthread_key_create(&recursiveLockWithDispatchQueueTLSKey, freeRecursiveLockWithDispatchQueueTLSValue);
        });
    
        RecursiveLockQueueBag* ms = reinterpret_cast<RecursiveLockQueueBag*>(pthread_getspecific(recursiveLockWithDispatchQueueTLSKey));
        if (!ms)
        {
            ms = new RecursiveLockQueueBag();
            pthread_setspecific(recursiveLockWithDispatchQueueTLSKey, reinterpret_cast<const void*>(ms));
        }
    
        const void* const vpq = reinterpret_cast<const void*>((__bridge const void*)q);
    
        BOOL alreadyOn = NO;
    
        if (checkAndPushNotPop)
        {
            alreadyOn = (ms->count(vpq) > 0);
            if (!alreadyOn)
            {
                ms->insert(vpq);
            }
        }
        else
        {
            ms->erase(vpq);
        }
        return alreadyOn;
    }
    
    void dispatch_recursive_sync(dispatch_queue_t queue, dispatch_block_t block)
    {
        if (queueStackCheck(queue, YES))
        {
            block();
        }
        else
        {
            @try
            {
                dispatch_sync(queue, block);
            }
            @finally
            {
                queueStackCheck(queue, NO);
            }
        }
    }
    
    @implementation MyAppDelegate
    
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
        dispatch_queue_t a = dispatch_queue_create("a", DISPATCH_QUEUE_SERIAL);
        dispatch_queue_t b = dispatch_queue_create("b", DISPATCH_QUEUE_SERIAL);
        dispatch_queue_t c = dispatch_queue_create("c", DISPATCH_QUEUE_SERIAL);
        //dispatch_set_target_queue(a, c);
    
        dispatch_recursive_sync(a, ^{
            dispatch_recursive_sync(b, ^{
                dispatch_recursive_sync(c, ^{
                    dispatch_recursive_sync(a, ^{
                        dispatch_recursive_sync(b, ^{
                            dispatch_recursive_sync(c, ^{
                                dispatch_recursive_sync(a, ^{
                                    NSLog(@"got there");
                                });
                            });
                        });
                    });
                });
            });
        });
    
    
    }
    
    @end
    

    This is the lowest-overhead implementation I could think of in a few minutes. I used C++ to avoid message sending overhead. It requires that all uses of the queue use this function. This can be useful when there's a private queue protecting internal state of an object (i.e. where the queue is private and therefore guaranteed not to be retargeted, and where you can easily ensure that all consumers of the queue use dispatch_recursive_sync.

    0 讨论(0)
提交回复
热议问题