Implementing next threading solutions in Swift / Objective-C

前端 未结 2 425
执念已碎
执念已碎 2021-01-29 07:44

I started to learn programming for iOS and I want to find out how to implement next Java functions with threads in Swi

2条回答
  •  日久生厌
    2021-01-29 08:33

    my answer for the first (1) solution (wait until all threads finish its execution):

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block1
        NSLog(@"Task Block1");
        [NSThread sleepForTimeInterval:6.0];
        NSLog(@"Task Block1 End");
    });
    
    
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        // block2
        NSLog(@"Task Block2");
        [NSThread sleepForTimeInterval:5.0];
        NSLog(@"Task Block2 End");
    });
    
    
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // blocks current thread
    

    for second solution (2)

    I didn't find for GCD method like isRunning, so I just use Boolean variable

    before starting async task set variable isRunning to true ... ... when async task is finished we can use next callback:

    dispatch_group_notify(_signInitThread, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        isRunning = false;
    });
    

提交回复
热议问题