线程间的通信 跨线程访问

跨线程访问本质是 对线程进行上锁,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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值