加锁 synchronize

来源:互联网 发布:炫酷导航页面源码 编辑:程序博客网 时间:2024/05/15 06:03



(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 = [NSStringstringWithFormat:@"tel:%@", phoneNumber];

    NSURL * url = [NSURL URLWithString:teluri];

    [[UIApplicationsharedApplication] openURL:url];



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

而不是对A进行加锁

//thread 1

m_strTest =@"0";//this is needed, form_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 = [NSStringstringWithFormat:@"%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 = [NSStringstringWithFormat:@"%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 = [NSStringstringWithFormat:@"%d", i];

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

}

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



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