多線程的安全隱患
- 當(dāng)多個線程訪問同一塊資源時,很容易引發(fā)數(shù)據(jù)錯亂和數(shù)據(jù)安全問題
安全隱患解決
方案一:使用“同步塊(synchronization block)”加一把互斥鎖
@synchronized(鎖對象) {
//需要鎖定的代碼
}
注意:鎖定1份代碼之用一把鎖,用多把鎖是無效的
-
同步塊(synchronization block)的優(yōu)缺點
- 優(yōu)點:能有效防止因多線程搶奪資源造成的數(shù)據(jù)安全問題
- 缺點:需要消耗大量的CPU資源(濫用@synchronized(鎖對象)會降低代碼效率,因為共用同一個鎖的同步塊,都必須按順序執(zhí)行,程序可能要等待另一段與此無關(guān)的代碼執(zhí)行完畢,才能繼續(xù)執(zhí)行當(dāng)前代碼,這樣沒必要)
- 同步塊(synchronization block)的使用前提:多條線程搶奪同一塊資源
同步塊(synchronization block)使用了線程同步技術(shù):多條線程在同一條線上執(zhí)行(多條線程本來是并發(fā)執(zhí)行的,線程同步之后,按順序的執(zhí)行任務(wù),為了保證不搶東西,一個線程做完另外一個線程做)
示例代碼
//
// ViewController.m
//
//
// Created by AYuan on 16/1/31.
// Copyright ? 2016年 AYuan. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
//為了在一開始創(chuàng)建線程不調(diào)用start也不死,這里搞一個強引用,因為創(chuàng)建一個進程如果沒有啟動它的話很有可能被銷毀
/**
售票員0
*/
@property (nonatomic, strong) NSThread *thread0;
/**
售票員1
*/
@property (nonatomic, strong) NSThread *thread1;
/**
售票員2
*/
@property (nonatomic, strong) NSThread *thread2;
/**
票總數(shù)
*/
@property (nonatomic, assign) NSInteger ticktCount;
/**
鎖對象
*/
@property (nonatomic, strong) NSObject *lockObj;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.ticktCount = 100;
self.lockObj = [[NSObject alloc] init];
self.thread0 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickts) object:nil];
self.thread0.name = @"售票員01";
self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickts) object:nil];
self.thread1.name = @"售票員02";
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickts) object:nil];
self.thread2.name = @"售票員3";
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.thread0 start];
[self.thread1 start];
[self.thread2 start];
}
- (void)saleTickts
{
while (1) {
@synchronized(self.lockObj) {
//先取出總數(shù)
NSInteger count = self.ticktCount;
if (count > 0) {
self.ticktCount = count - 1;
NSLog(@"%@賣出一張票,剩余%zd",[NSThread currentThread].name,self.ticktCount);
} else {
NSLog(@"票賣完了");
break;
}
}
}
}
@end
方案二:使用NSLock對象
_lock = [[NSLock alloc] init];
- (void)synchronizedMethod {
[_lock lock];
//safe
[_lock unlock];
}
方案三(筆者推薦用法):使用GCD
-
使用GCD的"串行同步隊列(serial synchronization queue)"將讀取操作及寫入操作都安排在同一個隊列里,即可保證數(shù)據(jù)同步
- 如果隊列中的塊執(zhí)行的任務(wù)簡單的話則用法如下:
_syncQueue = dispatch_queue_create("com.ayuan.syncQueue", NULL); - (NSString *)someString { __block NSString *localSomeString; dispatch_sync(_syncQueue, ^{ localSomeString = _someString; }); return localSomeString; } - (void)setSomeString:(NSString *)someString { dispatch_sync(_syncQueue, ^{ _someString = someString; });
}
- 如果隊列中的塊執(zhí)行的任務(wù)復(fù)雜則可以把同步派發(fā)改為異步派發(fā)
- (void)setSomeString:(NSString *)someString {
dispatch_async(_syncQueue, ^{
_someString = someString;
});
- 更高效的做法,使用同步隊列及柵欄塊:
- 在這個并發(fā)隊列中,讀取操作是用普通的塊來實現(xiàn)的,而寫入操作則是由柵欄塊來實現(xiàn)的,讀取操作可以并行,但寫入操作必須單獨執(zhí)行,因為它是柵欄塊
_syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
(NSString *)someString {
__block NSString *localSomeString;
dispatch_sync(_syncQueue, ^{
localSomeString = _someString;
});
return localSomeString;
}(void)setSomeString:(NSString *)someString {
dispatch_brrier_async(_syncQueue, ^{
_someString = someString;
});
}
##總結(jié)要點
- 使用GCD的同步語義比使用@synchronized塊或者NSLock對象更簡單
- 將同步與異步結(jié)合起來,可以實現(xiàn)同步加鎖,還不會阻塞異步線程
- 使用同步隊列及柵欄塊使同步行為更加高效