I started to learn programming for iOS and I want to find out how to implement next Java functions with threads in Swi
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");
});
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;
});