跨线程访问本质是 对线程进行上锁,NSCondition 条件锁
直接上代码。
@interface ViewController ()
{
NSCondition * _condition; //条件锁
// NSInteger _index;
}
//@property (nonatomic, strong) NSCondition *condition;
@property (nonatomic, assign) NSInteger index;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//先开两个线程
NSOperationQueue * q = [[NSOperationQueue alloc]init];
NSInvocationOperation * io1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(logOne) object:nil];
NSInvocationOperation * io2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(logTwo) object:nil];
// [io1 addDependency:io2];
[q addOperation:io1];
[q addOperation:io2];
_condition =[[NSCondition alloc]init]; //记得创建条件锁对象
_index = 0;
}
/// 必须先让改方法先执行。不然看不到效果
- (void)logOne{
[_condition lock];
while ( 1) {
[_condition wait]; //先让该线程 进入休眠等待状态
NSLog(@"--- %ld", ++_index);
[_condition signal]; //发送消息给其他线程来访问
}
// [_condition unlock]; // 猜测 siganl 和 wait 内部应该有unlock,这里可以不用unlock
}
- (void)logTwo{
[_condition lock];
while ( 1) {
NSLog(@"======== %ld", ++_index);
[_condition signal];
[_condition wait];
}
// [_condition unlock];
}
输出:
2017-04-18 16:03:37.686 TestThreadConnect[3903:1255568] 1111
2017-04-18 16:03:37.686 TestThreadConnect[3903:1255569] 2222
2017-04-18 16:03:37.687 TestThreadConnect[3903:1255569] ======== 1
2017-04-18 16:03:37.688 TestThreadConnect[3903:1255568] --- 2
2017-04-18 16:03:37.689 TestThreadConnect[3903:1255569] ======== 3
2017-04-18 16:03:37.689 TestThreadConnect[3903:1255568] --- 4
2017-04-18 16:03:37.690 TestThreadConnect[3903:1255569] ======== 5
2017-04-18 16:03:37.691 TestThreadConnect[3903:1255568] --- 6
2017-04-18 16:03:37.692 TestThreadConnect[3903:1255569] ======== 7
2017-04-18 16:03:37.693 TestThreadConnect[3903:1255568] --- 8
2017-04-18 16:03:37.693 TestThreadConnect[3903:1255569] ======== 9
2017-04-18 16:03:37.694 TestThreadConnect[3903:1255568] --- 10
2017-04-18 16:03:37.694 TestThreadConnect[3903:1255569] ======== 11
2017-04-18 16:03:37.695 TestThreadConnect[3903:1255568] --- 12
2017-04-18 16:03:37.695 TestThreadConnect[3903:1255569] ======== 13
2017-04-18 16:03:37.695 TestThreadConnect[3903:1255568] --- 14
2017-04-18 16:03:37.696 TestThreadConnect[3903:1255569] ======== 15