寫在前面, 開辟多線程是會(huì)占用更多內(nèi)存的, 不要濫開線程, 當(dāng)然現(xiàn)在iPhone內(nèi)存2G, 適當(dāng)?shù)氖褂檬菢O好的
如果有個(gè)需求, 在某一段代碼之后, 將后面代碼放入同步線程, 讓其等待前面代碼執(zhí)行完, 再執(zhí)行barrier之后的代碼, 用在一定要有先后順序的代碼, 比如創(chuàng)建完數(shù)據(jù)庫再創(chuàng)建表
先來個(gè)隊(duì)列屬性, 方便在不同作用域使用
@property (nonatomic, strong) dispatch_queue_t queue;
#pragma mark - 創(chuàng)建數(shù)據(jù)庫
- (void)createDataBase{
//創(chuàng)建并發(fā)隊(duì)列, 異步完成數(shù)據(jù)庫創(chuàng)建, 然后barrier同步等待數(shù)據(jù)庫創(chuàng)建之后, 創(chuàng)建表
_queue = dispatch_queue_create("com.10000114.ForDatabase",DISPATCH_QUEUE_CONCURRENT);
dispatch_async(_queue, ^{
[[NAFMDBHelper sharedFMDBHelper] createDatabase];
});
//等待數(shù)據(jù)庫創(chuàng)建完再創(chuàng)建表
dispatch_barrier_sync(_queue, ^{
[self createUserInfoTable];
});
}
#pragma mark - 創(chuàng)建表
- (void)createUserInfoTable{
//異步完成表的創(chuàng)建
dispatch_async(_queue, ^{
[[NAFMDBHelper sharedFMDBHelper] createUserInfoTable];
});
}
如果是同時(shí)執(zhí)行兩組代碼, 可以用Dispatch Group 和 Dispatch_set_target_queue , 但方便的話是dispatch_barrier_async, 這個(gè)我暫時(shí)還沒試驗(yàn)
例子
dispatch_queue_t queue = dispatch_queue_create(
"com.example.gcd.ForBarrier",DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue,blk0_for_reading);
dispatch_async(queue,blk1_for_reading);
dispatch_async(queue,blk2_for_reading);
//同時(shí)執(zhí)行一個(gè)
dispatch_barrier_async(queue,blk_for_writing);
dispatch_async(queue,blk3_for_reading);
dispatch_async(queue,blk4_for_reading);