之前遇到的面试题:如何用两个线程交替打印1-100的数字。
思路是使用信号量来控制两个线程的打印顺序。
代码如下:
/// 使用两个信号量来分别控制两个线程
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1); // wait该信号量的线程先输出
dispatch_semaphore_t semaphore_another = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
__block int num = 0;
dispatch_async(queue, ^{
while (YES) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
if (num >= 100) {
/// 当满足退出条件时,要先把另一个wait状态的信号量释放掉,否则会crash
dispatch_semaphore_signal(semaphore_another);
break;
}
NSLog(@"num: %i, thread: %@", num, [NSThread currentThread]);
num++;
dispatch_semaphore_signal(semaphore_another);
}
});
dispatch_async(queue, ^{
while (YES) {
dispatch_semaphore_wait(semaphore_another, DISPATCH_TIME_FOREVER);
if (num >= 100) {
dispatch_semaphore_signal(semaphore);
break;
}
NSLog(@"num: %i, thread: %@", num, [NSThread currentThread]);
num++;
dispatch_semaphore_signal(semaphore);
}
});
网友评论