加锁 synchronize



(gdb) p *((UIButton*)0x6d98ce0)

$1 = {

  <UIControl> = {

    <UIView> = {

      <UIResponder> = {

        <NSO


  _backgroundView = 0x6dc0210, 

  _imageView = 0x0, 

  _titleView = 0x6dc00c0, 

  _initialized = 1 '\001', 


(gdb) po 0x6dc00c0

<UIButtonLabel: 0x6dc00c0; frame = (15 6; 58 22); text = '记录(2)'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x6dc02d0>>

(gdb) 



//make a call 

NSString * teluri = [NSString stringWithFormat:@"tel:%@", phoneNumber];

    NSURL * url = [NSURL URLWithString:teluri];

    [[UIApplication sharedApplication] openURL:url];



@synchronized (A) {}  的本质就是根据一个标志A对一段代码进行加锁,开始处lock(sign), 结束时 unlock(sign)

而不是对A进行加锁

//thread 1

m_strTest = @"0";//this is needed, for m_strTest should not be nil, if it is nil, it won't work

@synchronized(m_strTest)

{

NSLog(@"@synchronized(m_strTest)");

sleep(200);

}


//thread 2

sleep(1);

NSLog(@"========= begin");

@synchronized(m_strTest)

{

m_strTest = [NSString stringWithFormat:@"%d", i];

NSLog(@"========= m_strTest is %@", m_strTest);

}

NSLog(@"========= end");


in this case, //thread 2 stopped at @synchronized(m_strTest)



sleep(1);

NSLog(@"========= begin");

//@synchronized(m_strTest)

{

m_strTest = [NSString stringWithFormat:@"%d", i];

NSLog(@"========= m_strTest is %@", m_strTest);

}

NSLog(@"========= end");



in this case, the code will run


===


m_strTest = @"0";

@synchronized(m_strTest)

{

NSLog(@"@synchronized(m_strTest)");

m_strTest = @"100";

sleep(200);

}



--

sleep(1);

NSLog(@"========= begin");

@synchronized(m_strTest)

{

m_strTest = [NSString stringWithFormat:@"%d", i];

NSLog(@"========= m_strTest is %@", m_strTest);

}

NSLog(@"========= end");



synchronized do not work at here, 代码都会执行到,因为 m_strTest 改变了,2个锁变量标识不一样




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值