多线程输出结果是不可控的,需要实现的结果是使用两个线程交替打印奇偶数
1.两个线程同时操作一个变量如:
_number = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(queue, ^{
while(_number<100) {
_number++;
NSLog(@"%ld",_number);
};
});
dispatch_async(queue, ^{
while(_number<100) {
_number++;
NSLog(@"%ld",_number);
};
});
会出现打印值顺序不确定,重复或其他不确定结果。
2.为了确定结果能顺序打印1-100,可以给线程加锁
_number = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
NSLock* lock = [[NSLockalloc]init];
dispatch_async(queue, ^{
while(_number<100) {
[lock lock];
NSLog(@"奇线程:%ld",_number);
_number++;
[lock unlock];
};
});
dispatch_async(queue, ^{
while(_number<100) {
[lock lock];
NSLog(@"偶线程:%ld",_number);
_number++;
[lock unlock];
};
});
这样可以保证结果是顺序输出,但保证不了奇线程打印奇数,偶线程打印偶数
3.我们可以使用条件锁来解决这个问题
_number = 0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
NSCondition* conditionLock = [[NSConditionalloc]init];
dispatch_async(queue, ^{
while(_number<100) {
[conditionLocklock];
if(_number%2!=0) {
NSLog(@"奇线程:%ld",(long)_number);
}
if(_number%2!=0) {
[conditionLocksignal];//激活偶线程
[conditionLockwait];//奇线程等待
}
_number++;
[conditionLockunlock];
};
});
dispatch_async(queue, ^{
while(_number<100) {
[conditionLocklock];
if(_number%2==0) {
NSLog(@"偶线程:%ld",(long)_number);
}
if(_number%2==0) {
[conditionLocksignal];//激活奇线程
[conditionLockwait];//偶线程等待
}
_number++;
[conditionLockunlock];
};
});