首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

GCD semphore 造成死锁的代码记录

2024-12-07 来源:要发发知识网
    dispatch_semaphore_t semphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_time_t waitetime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(50 * NSEC_PER_SEC));
    
    dispatch_async(queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"main");
            dispatch_semaphore_signal(semphore);
        });
        NSLog(@"async");
    });
    
    NSLog(@"lock");
    bool result = dispatch_semaphore_wait(semphore, waitetime);
    
    NSLog(@"unlock");
    if (result != 0) {
        NSLog(@"锁住了");
    }
    dispatch_semaphore_t semphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_time_t waitetime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(50 * NSEC_PER_SEC));


    dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"main");
            dispatch_semaphore_signal(semphore);
    });
    
    NSLog(@"lock");
    bool result = dispatch_semaphore_wait(semphore, waitetime);
    
    NSLog(@"unlock");
    if (result != 0) {
        NSLog(@"锁住了");
    }
显示全文