#import "ViewController.h" @interface ViewController () @property (nonatomic , strong) NSString *someString; @end @implementation ViewController { dispatch_queue_t _syncQueue; } - (void)viewDidLoad { [super viewDidLoad]; /** * GCD簡單高效的形式爲代碼加鎖 * */ //串行同步隊列 將讀取操做和寫入操做都安排在同一個隊列裏,便可保證數據同步。 _syncQueue = dispatch_queue_create("com.google.com", NULL); //併發隊列 _syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //GCD功能「阻斷器,柵欄」 //在隊列中柵欄必須單獨執行 void dispatch_barrier_async(dispatch_queue_t queue,dispatch_block_t block); void dispatch_barrier_sync(dispatch_queue_t queue,dispatch_block_t block); } //思路:把設置操做和獲取操做都安排在序列化的隊列執行 -(NSString *)someString{ __block NSString *localSomeString; dispatch_sync(_syncQueue, ^{ localSomeString = _someString; }); return localSomeString; } -(void)setsomeString:(NSString *)someString{ //同步派發 dispatch_sync(_syncQueue, ^{ _someString = someString; }); //異步派發 dispatch_async(_syncQueue, ^{ _someString = someString; }); //柵欄 dispatch_barrier_async(_syncQueue, ^{ _someString = someString; }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end