1 深拷貝淺拷貝
2 分類(lèi)不能添加成員變量
3 單例標(biāo)準(zhǔn)寫(xiě)法
4 weak弱引用
字符串拷貝分析
// 字符串拷貝分析
NSString *str = @"testStr";
NSString *str1 = [str copy];
NSMutableString *str2 = [str mutableCopy];
NSLog(@"str:%@,%p", str, str); // str: testStr ,0x10ac23020
NSLog(@"str1:%@,%p", str1, str1); // str1:testStr ,0x10ac23020
NSLog(@"str2:%@,%p", str2, str2); // str2:testStr ,0x60000112b720
// 總結(jié): string不可變字符串 copy淺拷貝 mutableCopy深拷貝
NSMutableString *mutStr = [[NSMutableString alloc] initWithString:@"123"];
NSString *mutStrCopy = [mutStr copy];
NSMutableString *mutStrMutCopy = [mutStr mutableCopy];
NSLog(@"mutStr:%@,%p", mutStr, mutStr); // mutStr:123, 0x6000039cf6c0
NSLog(@"mutStrCopy:%@,%p", mutStrCopy, mutStrCopy); // mutStrCopy:123, 0x984f4eaff626b56e
NSLog(@"mutStrMutCopy:%@,%p", mutStrMutCopy, mutStrMutCopy); // mutStrMutCopy:123,0x6000039ce850
// 總結(jié): mutableString可變字符串 copy 和 mutableCopy 都是深拷貝
}
屬性字符串深/淺拷貝
@property (nonatomic, strong) NSString* strString;
@property (nonatomic, copy) NSString* copString;
NSMutableString* textString = [[NSMutableString alloc] initWithString:@"str"];
self.strString = textString; // strong
self.copString = textString; // copy
NSLog(@"\n初始值\ntextSting:%@,\nstrongString:%@,\ncopyString:%@",textString,_strString,_copString);
/*
初始值
textSting: str,
strongString:str,
copyString: str
*/
NSLog(@"\n初始內(nèi)存地址\ntextSting:%p,\nstrongString:%p,\ncopyString:%p",textString,_strString,_copString);
/*
初始內(nèi)存地址
textSting: 0x60000198d500,
strongString:0x60000198d500,
copyString: 0x9a6b751948ecb1a9 */
[textString appendString:@"str"];
NSLog(@"\n修改后值\ntextSting:%@,\nstrongString:%@,\ncopyString:%@",textString,_strString,_copString);
/*修改后值
textSting: strstr,
strongString:strstr,
copyString: str */
NSLog(@"\n修改后內(nèi)存地址\ntextSting:%p,\nstrongString:%p,\ncopyString:%p",textString,_strString,_copString);
/*
修改后內(nèi)存地址
textSting: 0x60000198d500,
strongString: 0x60000198d500,
copyString: 0x9a6b751948ecb1a9
*/
/**
總結(jié): strong 淺拷貝 copy深拷貝
*/
數(shù)組拷貝分析
NSMutableString *testStr = [@"123" mutableCopy];
// array可變數(shù)組
NSArray *arr = @[@"1", @"2", testStr];
// arr = @[@"1", @"2", @"123"]
NSArray *arrCopy = [arr copy];
NSMutableArray *arrMutablecopy = [arr mutableCopy];
NSLog(@"===arr:%@,%p \nobjectP:%p", arr, arr, arr[0]); // 原數(shù)組 array
// arr:(1, 2) ,0x600002979e60 , objectP:0x10623c168
NSLog(@"arrCopy:%@,%p \nobjectP:%p", arrCopy, arrCopy, arrCopy[0]); // copy后
// arr:(1, 2) ,0x600002979e60 , objectP:0x10623c168
NSLog(@"arrMutablecopy:%@,%p \nobjectP:%p", arrMutablecopy, arrMutablecopy, arrMutablecopy[0]); // mutableCopy后
// arrMutablecopy:(1,2),0x60000270a430 , objectP:0x10623c168
// 總結(jié) 不可變數(shù)組, copy淺拷貝, mutableCopy深拷貝
[testStr appendString:@"45"];
NSLog(@"arr:%@,%p \nobjectP:%p", arr, arr, arr[0]); //原數(shù)組 array 元素修改后
// arr:(1, 2, 12345) ,0x600002979e60 , objectP:0x10623c168
NSLog(@"arrCopy:%@,%p \nobjectP:%p", arrCopy, arrCopy, arrCopy[0]); // copy后
// arr:(1, 2, 12345) ,0x600002979e60 , objectP:0x10623c168
NSLog(@"arrMutablecopy:%@,%p \nobjectP:%p", arrMutablecopy, arrMutablecopy, arrMutablecopy[0]); // mutableCopy后
// arrMutablecopy:(1,2,12345),0x60000270a430 , objectP:0x10623c168
// 修改元素后總結(jié) 不可變數(shù)組, copy淺拷貝, mutableCopy深拷貝
// 總結(jié) 對(duì)array copy 淺拷貝斟湃,mutableCopy 深拷貝 勿决,但是,mutableCopy后,arrMutablecopy里面的元素 與 原arr里面的元素地址相同骗卜,所以array的mutableCopy是不完全深拷貝峭沦,只深拷貝了第一層跌造,沒(méi)有深拷貝內(nèi)層
/*=============================================================================================*/
NSMutableString *mutarrTestStr = [@"abc" mutableCopy];
// mutableArray 不可變數(shù)組
NSMutableArray *mutarr = [NSMutableArray arrayWithObjects:@"123", mutarrTestStr, nil];
// mutarr = @[@"123", @"abc"]
NSArray *mutarrCopy = [mutarr copy];
NSMutableArray *mutarrMutablecopy = [mutarr mutableCopy];
NSLog(@"mutarr:%@,%p \nobjectP:%p", mutarr, mutarr, mutarr[0]); // 原數(shù)組 mutableArray
// arr:(123, abc) ,0x600001396460 , objectP:0x1015bc0e8
NSLog(@"mutarrCopy:%@,%p \nobjectP:%p", mutarrCopy, mutarrCopy, mutarrCopy[0]); // copy后
// arr:(123, abc) ,0x600001396460 , objectP:0x1015bc0e8
NSLog(@"mutarrMutablecopy:%@,%p \nobjectP:%p", mutarrMutablecopy, mutarrMutablecopy, mutarrMutablecopy[0]); // mutableCopy后
// arrMutablecopy:(123,abc),0x60000270a430 , objectP:0x1015bc0e8
// 總結(jié) 數(shù)組copy 淺拷貝; mutableCopy 深拷貝, 數(shù)組元素淺拷貝(都一樣)
[mutarrTestStr appendString:@"456"]; //數(shù)組 元素修改后
// mutarr = @[@"123", @"abc456"]
NSLog(@"mutarr:%@,%p \nobjectP:%p", mutarr, mutarr, mutarr[0]); //原數(shù)組 mutableArray 元素修改后
// arr:(123, abc456) ,0x600001396460 , objectP:0x1015bc0e8
NSLog(@"mutarrCopy:%@,%p \nobjectP:%p", mutarrCopy, mutarrCopy, mutarrCopy[0]); // copy后
// arr:(123, abc456) ,0x600001396460 , objectP:0x1015bc0e8
NSLog(@"mutarrMutablecopy:%@,%p \nobjectP:%p", mutarrMutablecopy, mutarrMutablecopy, mutarrMutablecopy[0]); // mutableCopy后
// arrMutablecopy:(123,abc456),0x60000270a430 , objectP:0x1015bc0e8
// 總結(jié) 數(shù)組元素變動(dòng) 和上面地址一樣
// 1.對(duì)于不可變對(duì)象而言埠胖,copy便是淺拷貝,mutableCopy是深拷貝
// 2.對(duì)于可變對(duì)象而言笤虫,copy和mutableCopy都是深拷貝旁瘫,但是copy出來(lái)的對(duì)象是不可變的,而mutableCopy出來(lái)的對(duì)象是可變的
// 3. 對(duì)于容器類(lèi)型來(lái)說(shuō)琼蚯,mutableCopy 僅僅拷貝了第一層酬凳,所以是不完全深拷貝
屬性數(shù)組 深/淺拷貝
@property (nonatomic, strong) NSArray* strongArray;
@property (nonatomic, copy) NSArray* copyedArray;
// 一 可變數(shù)組
NSMutableArray *muArray = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3"]];
self.strongArray = muArray;
self.copyedArray = muArray;
NSLog(@"muArray地址:%p,數(shù)據(jù):%@",muArray,muArray); // muArray地址: 0x600000bafde0, 數(shù)據(jù):(1, 2, 3 )
NSLog(@"strongArray地址:%p,數(shù)據(jù):%@",_strongArray,_strongArray); // strongArray地址:0x600000bafde0, 數(shù)據(jù):(1, 2, 3 )
NSLog(@"copyedArray地址:%p,數(shù)據(jù):%@",_copyedArray,_copyedArray); // copyedArray地址:0x600000bafbd0, 數(shù)據(jù):(1, 2, 3 )
[muArray addObject:@"4"]; // 數(shù)據(jù)修改后
NSLog(@"muArray地址:%p,數(shù)據(jù):%@",muArray,muArray); // muArray地址: 0x600000bafde0, 數(shù)據(jù):(1, 2, 3 , 4)
NSLog(@"strongArray地址:%p,數(shù)據(jù):%@",_strongArray,_strongArray); // strongArray地址:0x600000bafde0, 數(shù)據(jù):(1, 2, 3 , 4)
NSLog(@"copyedArray地址:%p,數(shù)據(jù):%@",_copyedArray,_copyedArray); // copyedArray地址:0x600000bafbd0, 數(shù)據(jù):(1, 2, 3 )
//總結(jié): 可變數(shù)組 賦值: strongArray 淺拷貝 copyedArray 深拷貝
// 二 不可變數(shù)組
NSArray *array = @[@"1",@"2",@"3"];
self.strongArray = array;
self.copyedArray = array;
NSLog(@"array地址:%p,數(shù)據(jù):%@",array,array); // array地址: 0x6000035be340, 數(shù)據(jù):(1, 2, 3 )
NSLog(@"strongArray地址:%p,數(shù)據(jù):%@",_strongArray,_strongArray); // strongArray地址:0x6000035be340, 數(shù)據(jù):(1, 2, 3 )
NSLog(@"copyedArray地址:%p,數(shù)據(jù):%@",_copyedArray,_copyedArray); // copyedArray地址:0x6000035be340, 數(shù)據(jù):(1, 2, 3 )
//總結(jié): 不可變數(shù)組 賦值: strongArray 淺拷貝 copyedArray 淺拷貝
link: http://www.reibang.com/p/7c38856b3231
分類(lèi) 屬性
Objective-C類(lèi)是由Class類(lèi)型來(lái)表示的,它實(shí)際上是一個(gè)指向objc_class結(jié)構(gòu)體的指針凌停。它的定義如下:
typedef struct objc_class *Class;
objc_class結(jié)構(gòu)體的定義如下:
struct objc_class {
Class isa OBJC_ISA_AVAILABILITY; // isa指針
#if !__OBJC2__
Class super_class OBJC2_UNAVAILABLE; // 父類(lèi)
const char *name OBJC2_UNAVAILABLE; // 類(lèi)名
long version OBJC2_UNAVAILABLE; // 類(lèi)的版本信息
long info OBJC2_UNAVAILABLE; // 類(lèi)信息
long instance_size OBJC2_UNAVAILABLE; // 該類(lèi)的實(shí)例變量大小
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE; // 該類(lèi)的成員變量鏈表
struct objc_method_list **methodLists OBJC2_UNAVAILABLE; // 方法定義的鏈表
struct objc_cache *cache OBJC2_UNAVAILABLE; // 方法緩存
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE; // 協(xié)議鏈表
#endif
}
為什么不能添加成員變量呢粱年?
在上面的objc_class結(jié)構(gòu)體中,
ivars是objc_ivar_list(成員變量列表)指針罚拟;
methodLists是指向objc_method_list指針的指針台诗。
在Runtime中,objc_class結(jié)構(gòu)體大小是固定的赐俗,long instance_size 標(biāo)識(shí)實(shí)例變量大小,不可能往這個(gè)結(jié)構(gòu)體中添加數(shù)據(jù)拉队,只能修改。所以ivars指向的是一個(gè)固定區(qū)域阻逮,只能修改成員變量值粱快,不能增加成員變量個(gè)數(shù)。methodList是一個(gè)二維數(shù)組叔扼,所以可以修改*methodLists的值來(lái)增加成員方法事哭,雖沒(méi)辦法擴(kuò)展methodLists指向的內(nèi)存區(qū)域,卻可以改變這個(gè)內(nèi)存區(qū)域的值(存儲(chǔ)的是指針)瓜富。因此鳍咱,可以動(dòng)態(tài)添加方法,不能添加成員變量与柑。
link http://www.reibang.com/p/e203d70ccc3f
單例
#import "FTManager.h"
static FTManager *manager = nil;
@implementation FTManager
+ (instancetype)shareManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// manager = [[FTManager alloc] init];
manager = [[super allocWithZone:NULL] init] ;
});
return manager;
}
// 保證 [[FTManager alloc] init] 對(duì)象地址統(tǒng)一
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [FTManager shareManager];
}
// 保證 [[[FTManager alloc] init] copy] 對(duì)象地址統(tǒng)一
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
return [FTManager shareManager];
}
@end
NSLog(@"%p",[FTManager shareManager]);
NSLog(@"%p",[[FTManager alloc] init]);
NSLog(@"%p",[[[FTManager alloc] init] copy]);
2022-04-19 14:14:41.308590+0800 ForTest[3773:68879] 0x6000014faa30
2022-04-19 14:14:41.308763+0800 ForTest[3773:68879] 0x6000014faa30
2022-04-19 14:14:41.308916+0800 ForTest[3773:68879] 0x6000014faa30
weak
1.weak的作用
weak 關(guān)鍵字的作用弱引用谤辜,所引用對(duì)象的計(jì)數(shù)器不會(huì)加一,并在引用對(duì)象被釋放的時(shí)候自動(dòng)被設(shè)置為 nil价捧。
2.weak的實(shí)現(xiàn)原理
第一丑念、通過(guò)weak編譯解析,可以看出來(lái)weak通過(guò)runtime初始化的并維護(hù)的结蟋;
第二脯倚、weak和strong都是Object-C的修飾詞,而strong是通過(guò)runtime維護(hù)的一個(gè)自動(dòng)計(jì)數(shù)表結(jié)構(gòu)椎眯。
綜上:weak是有Runtime維護(hù)的weak表挠将。
3.weak釋放為nil過(guò)程
weak被釋放為nil胳岂,需要對(duì)對(duì)象整個(gè)釋放過(guò)程了解编整,如下是對(duì)象釋放的整體流程:
1舔稀、調(diào)用objc_release
2、因?yàn)閷?duì)象的引用計(jì)數(shù)為0掌测,所以執(zhí)行dealloc
3内贮、在dealloc中,調(diào)用了_objc_rootDealloc函數(shù)
4汞斧、在_objc_rootDealloc中夜郁,調(diào)用了object_dispose函數(shù)
5、調(diào)用objc_destructInstance
6粘勒、最后調(diào)用objc_clear_deallocating竞端。
http://www.reibang.com/p/f331bd5ce8f8
信號(hào)量
在IOS系統(tǒng)GCD的semaphore.h頭文件中提供三個(gè)方法進(jìn)行PV操作
// 這value是初始化多少個(gè)信號(hào)量
1.dispatch_semaphore_create(long value);
// 這個(gè)方法是P操作對(duì)信號(hào)量減一,dsema這個(gè)參數(shù)表示對(duì)哪個(gè)信號(hào)量進(jìn)行減一庙睡,如果該信號(hào)量為0則等待事富,timeout這個(gè)參數(shù)則是傳入等待的時(shí)長(zhǎng)。
2.dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout);
// 這個(gè)方法是V操作對(duì)信號(hào)量加一乘陪,dsema這個(gè)參數(shù)表示對(duì)哪個(gè)信號(hào)量進(jìn)行加一
3.dispatch_semaphore_signal(dispatch_semaphore_t dsema);
@interface FTTestViewController ()
/// iphone的數(shù)量
@property (nonatomic,assign) int iphoneNumber;
/// 互斥用的信號(hào)量
@property (nonatomic,strong) dispatch_semaphore_t semaphore;
@end
@implementation FTTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self test];
}
- (void)test {
self.iphoneNumber = 10;
// 初始化1個(gè)信號(hào)量
self.semaphore = dispatch_semaphore_create(1);
/// 通過(guò)信號(hào)量進(jìn)行互斥统台,開(kāi)啟三個(gè)窗口(線程)同時(shí)賣(mài)iphone
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
thread1.name = @"窗口1";
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
thread2.name = @"窗口2";
NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
thread3.name = @"窗口3";
[thread1 start];
[thread2 start];
[thread3 start];
}
// 通過(guò)信號(hào)量達(dá)到互斥
- (void)sellIphone
{
while (1) {
// P操作對(duì)信號(hào)量進(jìn)行減一,然后信號(hào)量變0啡邑,限制其他窗口(線程)進(jìn)入
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
if (self.iphoneNumber > 0) // 檢查還有沒(méi)iphone可賣(mài)
{
NSLog(@"賣(mài)出iphone剩下%d臺(tái)iphone---fromThread:%@",--self.iphoneNumber,[NSThread currentThread]);
}
else
{
NSLog(@"iphone沒(méi)有庫(kù)存了");
return;
}
// V操作對(duì)信號(hào)量進(jìn)行加一贱勃,然后信號(hào)量為1,其他窗口(線程)就能進(jìn)入了
dispatch_semaphore_signal(self.semaphore);
}
}
2022-04-20 14:15:38.484988+0800 ForTest[19430:548682] 賣(mài)出iphone剩下9臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd80>{number = 9, name = 窗口3}
2022-04-20 14:15:38.485890+0800 ForTest[19430:548680] 賣(mài)出iphone剩下8臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd00>{number = 7, name = 窗口1}
2022-04-20 14:15:38.487929+0800 ForTest[19430:548681] 賣(mài)出iphone剩下7臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd40>{number = 8, name = 窗口2}
2022-04-20 14:15:38.489221+0800 ForTest[19430:548682] 賣(mài)出iphone剩下6臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd80>{number = 9, name = 窗口3}
2022-04-20 14:15:38.490322+0800 ForTest[19430:548680] 賣(mài)出iphone剩下5臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd00>{number = 7, name = 窗口1}
2022-04-20 14:15:38.491334+0800 ForTest[19430:548681] 賣(mài)出iphone剩下4臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd40>{number = 8, name = 窗口2}
2022-04-20 14:15:38.492223+0800 ForTest[19430:548682] 賣(mài)出iphone剩下3臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd80>{number = 9, name = 窗口3}
2022-04-20 14:15:38.492808+0800 ForTest[19430:548680] 賣(mài)出iphone剩下2臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd00>{number = 7, name = 窗口1}
2022-04-20 14:15:38.493185+0800 ForTest[19430:548681] 賣(mài)出iphone剩下1臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd40>{number = 8, name = 窗口2}
2022-04-20 14:15:38.498118+0800 ForTest[19430:548682] 賣(mài)出iphone剩下0臺(tái)iphone---fromThread:<NSThread: 0x600001cbbd80>{number = 9, name = 窗口3}
2022-04-20 14:15:38.499101+0800 ForTest[19430:548680] iphone沒(méi)有庫(kù)存了
/// 通過(guò)同步鎖進(jìn)行互斥谤逼,通過(guò)同步鎖會(huì)比通過(guò)信號(hào)量控制的方式多進(jìn)入該臨界代碼(線程數(shù)量-1)次
- (void)sellIphoneWithSynchronization
{
while (1) {
@synchronized (self) {
if (self.iphoneNumber > 0) // 檢查還有沒(méi)iphone可賣(mài)
{
NSLog(@"%@賣(mài)出iphone剩下%d臺(tái)iphone",[NSThread currentThread].name,--self.iphoneNumber);
}
else
{
NSLog(@"iphone沒(méi)有庫(kù)存了");
return;
}
}
}
}
@end
link https://blog.csdn.net/fanyun_01/article/details/111878096
隊(duì)列 隊(duì)列組 柵欄函數(shù) 線程死鎖
隊(duì)列
/* ##### 隊(duì)列任務(wù) */
// 一: 同步串行隊(duì)列
// 參數(shù)1 隊(duì)列名字 參數(shù)2 串行隊(duì)列宏
dispatch_queue_t queue1 = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);
for(NSInteger i = 0; i < 10; i++){
// 同步任務(wù) 添加到串行隊(duì)列
dispatch_sync(queue1, ^{
NSLog(@"thread == %@ i====%ld",[NSThread currentThread],(long)i);
// thread == <_NSMainThread: 0x6000002c0000>{number = 1, name = main} i====8
// thread == <_NSMainThread: 0x6000002c0000>{number = 1, name = main} i====9
});
}
// ps: 主線程 同步串行執(zhí)行任務(wù)
// 二: 同步并行隊(duì)列
dispatch_queue_t queue2 = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
for(NSInteger i = 0; i < 10; i++){
dispatch_sync(queue2, ^{
NSLog(@"thread == %@ i====%ld",[NSThread currentThread],(long)i);
});
}
// ps: 主線程 同步執(zhí)行任務(wù)
//三: 異步串行隊(duì)列
dispatch_queue_t queue3 = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);
for(NSInteger i = 0; i < 10; i++){
dispatch_async(queue3, ^{
NSLog(@"thread == %@ i====%ld",[NSThread currentThread],(long)i);
});
}
// ps: 開(kāi)辟一條子線程 串行執(zhí)行任務(wù)
//四: 異步并行隊(duì)列
dispatch_queue_t queue4 = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
for(NSInteger i = 0; i < 10; i++){
dispatch_async(queue4, ^{
NSLog(@"thread == %@ i====%ld",[NSThread currentThread],(long)i);
});
// thread == <NSThread: 0x600001104700>{number = 4, name = (null)} i====7
// thread == <NSThread: 0x6000024cb900>{number = 11, name = (null)} i====8
// thread == <NSThread: 0x6000024f5340>{number = 5, name = (null)} i====9
}
// ps: 開(kāi)辟多條子線程 并行執(zhí)行任務(wù)
// 開(kāi)辟線程主要看 dispatch_async 異步
//五: 異步 主隊(duì)列
dispatch_queue_t queue5 = dispatch_get_main_queue();
for(NSInteger i = 0; i < 10; i++){
sleep(2);
dispatch_async(queue5, ^{
NSLog(@"thread == %@ i====%ld",[NSThread currentThread],(long)i);
});
}
// ps: 主線程 串行執(zhí)行任務(wù)
隊(duì)列組
// 六: 隊(duì)列組
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, concurrentQueue, ^{
for (int i = 0; i < 3; i++)
{
NSLog(@"Task1 %@ %d", [NSThread currentThread], i);
}
});
dispatch_group_async(group, dispatch_get_main_queue(), ^{
for (int i = 0; i < 3; i++)
{
NSLog(@"Task2 %@ %d", [NSThread currentThread], i);
}
});
dispatch_group_async(group, concurrentQueue, ^{
for (int i = 0; i < 3; i++)
{
NSLog(@"Task3 %@ %d", [NSThread currentThread], i);
} //
});
dispatch_group_notify(group, concurrentQueue, ^{
NSLog(@"All Task Complete");
});
Task3 <NSThread: 0x600000bcf400>{number = 5, name = (null)} 0
Task1 <NSThread: 0x600000b8a740>{number = 8, name = (null)} 0
Task3 <NSThread: 0x600000bcf400>{number = 5, name = (null)} 1
Task1 <NSThread: 0x600000b8a740>{number = 8, name = (null)} 1
Task3 <NSThread: 0x600000bcf400>{number = 5, name = (null)} 2
Task1 <NSThread: 0x600000b8a740>{number = 8, name = (null)} 2
Task2 <_NSMainThread: 0x600000be8980>{number = 1, name = main} 0
Task2 <_NSMainThread: 0x600000be8980>{number = 1, name = main} 1
Task2 <_NSMainThread: 0x600000be8980>{number = 1, name = main} 2
All Task Complete
// ps 異步并行隊(duì)列 正常會(huì)開(kāi)啟n調(diào)線程 這里只開(kāi)啟了一條線程???
柵欄函數(shù)
柵欄函數(shù)的作?:
1 實(shí)現(xiàn)多讀單寫(xiě), 當(dāng)鎖用
2 控制線程執(zhí)行順序, 達(dá)到同步的效果
柵欄函數(shù)注意:
1 柵欄函數(shù)只能控制同一并發(fā)隊(duì)列
2 柵欄函數(shù)要想起作用贵扰,那么創(chuàng)建任務(wù)隊(duì)列就必須使用dispatch_queue_create()該種方式,使用全局隊(duì)列柵欄函數(shù)無(wú)法發(fā)揮作用流部;
dispatch_barrier_async:前面的任務(wù)執(zhí)行完畢戚绕,才會(huì)來(lái)到這里
dispatch_barrier_sync:作用相同,但是這個(gè)會(huì)堵塞線程贵涵,影響后面的執(zhí)行
@interface FTTestViewController ()
{
// 定義一個(gè)并發(fā)隊(duì)列
dispatch_queue_t _concurrent_queue;
// 用戶(hù)數(shù)據(jù)中心, 可能多個(gè)線程需要數(shù)據(jù)訪問(wèn)
NSMutableDictionary *_userCenterDic;
}
- (void)viewDidLoad {
[super viewDidLoad];
//七: 柵欄函數(shù)
// 多讀單寫(xiě)
// 通過(guò)宏定義 DISPATCH_QUEUE_CONCURRENT 創(chuàng)建一個(gè)并發(fā)隊(duì)列
_concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
// 創(chuàng)建數(shù)據(jù)容器
_userCenterDic = [NSMutableDictionary dictionary];
[self barrierTest]; // 柵欄函數(shù)測(cè)試
}
- (id)objectForKey:(NSString *)key
{
__block id obj;
// 同步讀取指定數(shù)據(jù),立刻返回讀取結(jié)果
dispatch_sync(_concurrent_queue, ^{
obj = [self->_userCenterDic objectForKey:key];
});
return obj;
}
- (void)setObject:(id)obj forKey:(NSString *)key
{
// 異步柵欄調(diào)用設(shè)置數(shù)據(jù)
dispatch_barrier_async(_concurrent_queue, ^{
[self->_userCenterDic setObject:obj forKey:key];
});
}
// 柵欄函數(shù)測(cè)試 舉例
- (void)barrierTest {
// 建立全局并發(fā)隊(duì)列
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^{
NSLog(@"任務(wù)(一)%@",[NSThread currentThread]);
});
dispatch_async(concurrentQueue, ^{
NSLog(@"任務(wù)(二)%@",[NSThread currentThread]);
});
dispatch_async(concurrentQueue, ^{
NSLog(@"任務(wù)(三)%@",[NSThread currentThread]);
});
dispatch_barrier_async(concurrentQueue, ^{
NSLog(@"(柵欄函數(shù))%@",[NSThread currentThread]);
});
dispatch_async(concurrentQueue, ^{
NSLog(@"任務(wù)(四)%@",[NSThread currentThread]);
});
NSLog(@"開(kāi)始工作");
}
2022-04-20 19:11:49.205886+0800 ForTest[26101:755643] 開(kāi)始工作
2022-04-20 19:11:49.206003+0800 ForTest[26101:755903] 任務(wù)(二)<NSThread: 0x600002ceb140>{number = 4, name = (null)}
2022-04-20 19:11:49.206010+0800 ForTest[26101:755908] 任務(wù)(一)<NSThread: 0x600002c9a1c0>{number = 6, name = (null)}
2022-04-20 19:11:49.206041+0800 ForTest[26101:755901] 任務(wù)(三)<NSThread: 0x600002c89c00>{number = 3, name = (null)}
2022-04-20 19:11:49.206232+0800 ForTest[26101:755908] (柵欄函數(shù))<NSThread: 0x600002c9a1c0>{number = 6, name = (null)}
2022-04-20 19:11:49.206398+0800 ForTest[26101:755901] 任務(wù)(四)<NSThread: 0x600002c89c00>{number = 3, name = (null)}
線程死鎖
觸發(fā)場(chǎng)景: 主線程/同步 串行隊(duì)列/同步 死鎖
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_sync(queue, ^{
NSLog(@"執(zhí)行任務(wù)2"); // Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
});// 往主線程里面 同步添加任務(wù) 會(huì)發(fā)生死鎖現(xiàn)象
dispatch_queue_t myQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{ // 異步串行隊(duì)列
NSLog(@"1111,thread====%@",[NSThread currentThread]);
dispatch_sync(myQueue, ^{ // 同步串行隊(duì)列
NSLog(@"2222,thread====%@",[NSThread currentThread]);
// Thread 4: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) crash
});
});