Implementing next threading solutions in Swift / Objective-C

前端 未结 2 429
执念已碎
执念已碎 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:25

    For 2, I would use serial queue:

    dispatch_queue_t myQueue;
    

    And implement my queue as of below:

    myQueue = dispatch_queue_create("my_serial_queue", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(myQueue, ^{
        for (int i = 0; i < 10000; i++) {
            usleep(100);
        }
        NSLog(@"Task 1 done");
    });
    
    dispatch_async(myQueue, ^{
        NSLog(@"Task 2 done");
    });
    
    0 讨论(0)
  • 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;
    });
    
    0 讨论(0)
提交回复
热议问题