因為performSelector方法是需要依賴線程runLoop总寒,但是開辟的子線程默認是沒有開啟runLoop的,所以方法調(diào)用不生效
PerformSelector詳細總結(jié)
#import "UserCenter.h"
@interface UserCenter()
{
// 定義一個并發(fā)隊列
dispatch_queue_t concurrent_queue;
// 用戶數(shù)據(jù)中心, 可能多個線程需要數(shù)據(jù)訪問
NSMutableDictionary *userCenterDic;
}
@end
// 多讀單寫模型
@implementation UserCenter
- (id)init
{
self = [super init];
if (self) {
// 通過宏定義 DISPATCH_QUEUE_CONCURRENT 創(chuàng)建一個并發(fā)隊列
concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
// 創(chuàng)建數(shù)據(jù)容器
userCenterDic = [NSMutableDictionary dictionary];
}
return self;
}
- (id)objectForKey:(NSString *)key
{
__block id obj;
// 同步讀取指定數(shù)據(jù)
dispatch_sync(concurrent_queue, ^{
obj = [userCenterDic objectForKey:key];
});
return obj;
}
- (void)setObject:(id)obj forKey:(NSString *)key
{
// 異步柵欄調(diào)用設(shè)置數(shù)據(jù)
dispatch_barrier_async(concurrent_queue, ^{
[userCenterDic setObject:obj forKey:key];
});
}
@end
dispatch_group_async的使用
#import "GroupObject.h"
@interface GroupObject()
{
dispatch_queue_t concurrent_queue;
NSMutableArray <NSURL *> *arrayURLs;
}
@end
@implementation GroupObject
- (id)init
{
self = [super init];
if (self) {
// 創(chuàng)建并發(fā)隊列
concurrent_queue = dispatch_queue_create("concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
arrayURLs = [NSMutableArray array];
}
return self;
}
- (void)handle
{
// 創(chuàng)建一個group
dispatch_group_t group = dispatch_group_create();
// for循環(huán)遍歷各個元素執(zhí)行操作
for (NSURL *url in arrayURLs) {
// 異步組分派到并發(fā)隊列當(dāng)中
dispatch_group_async(group, concurrent_queue, ^{
//根據(jù)url去下載圖片
NSLog(@"url is %@", url);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 當(dāng)添加到組中的所有任務(wù)執(zhí)行完成之后會調(diào)用該Block
NSLog(@"所有圖片已全部下載完成");
});
}
@end
重入導(dǎo)致了死鎖狞谱,這種場景可以將NSLock換成遞歸鎖