Cocoa多線程編程筆記:NSLock與NSThread



//

#import <Foundation/Foundation.h>

//int main(int argc, const char * argv[])
//{
//
//    @autoreleasepool {
//        
//        // insert code here...
//        NSLog(@"Hello, World!");
//        
//    }
//    return 0;
//}

NSLock *lock;  
@interface MyObject : NSObject  
+(void)aMethod:(id)param;  
@end  
@implementation MyObject  
+(void)aMethod:(id)param{  
    int x;  
    for(x=0;x<50;++x)  
    {  
        [lock lock];  
        NSLog(@"Object Thread says x is %i\n",x);  
        usleep(10);  //語句A
        [lock unlock];  
    }  
    NSLog(@"==Object thread return==");
    return;
   }  
@end  
int main(int argc, char *argv[])  
{   
    int x;  
    lock = [[NSLock alloc] init];  
    [NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:[MyObject class] withObject:nil];  
    
    for(x=0;x<50;++x)  
    {  
        [lock lock];  
        NSLog(@"Main thread says x is %i\n",x);  
        usleep(10);  //語句B
        [lock unlock];  
        usleep(10);  //語句C
    }  
    NSLog(@"==Main thread return==");
    usleep(300); //語句D
    return 0;  
}  



(1)通過NSThread建立線程

(2)通過NSLock進行線程同步,lock與unlock之間代碼可以保證在多個線程間保證原子操作。

a:去掉主線程與子線程中的NSLock相關語句後,通過打印發現;2個線程之間打印的順序隨機;

b:通過使用NSLock, 無論語句A與語句B的值設置爲多大,兩個線程會交替執行(我把語句C設置爲10,保證子線程有進入機會);說明NSLcok保證了lock代碼段的原子操作。

c: 主線程退出後,子線程也會退出。 通過修改語句D的值較大時,子線程有足夠時間退出,可以打印“Object thread return”,較小時不一定會打印出來。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章