1. 多線程技術(shù)
1). NSThread :
1. 使用NSThread對象建立一個(gè)線程非常方便;
2. 但是!要使用NSThread管理多個(gè)線程非常困難,不推薦使用;
3. 技巧!使用[NSThread currentThread]跟蹤任務(wù)所在線程,適用于這三種技術(shù).
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadRun) object:nil];
[thread setName:@"first"];
[thread start];
2). NSOperation:
1.提供了一些在GCD中不容易實(shí)現(xiàn)的特性,如:限制最大并發(fā)數(shù)量,操作之間的依賴關(guān)系.
2.NSOperation有狀態(tài)返回,能控制其取消等操作,推薦使用多線程的時(shí)候用這種方式,靈活
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runInvocationOperation) object:nil];
[invocationOperation setQueuePriority:NSOperationQueuePriorityVeryHigh];
NSInvocationOperation *invocationOperation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runInvocationOperation) object:nil];
[invocationOperation1 setQueuePriority:NSOperationQueuePriorityLow];
[invocationOperation1 addDependency:invocationOperation];//增加依賴,某個(gè)任務(wù)完成,才開始這個(gè)任務(wù)
[invocationOperation cancel];//取消動作
[invocationOperation start];//開始動作
BOOL isExe = invocationOperation.isExecuting;//是否執(zhí)行中
BOOL isFinish = invocationOperation.isFinished;//是否結(jié)束了
self.queue = [[NSOperationQueue alloc]init];
[self.queue setMaxConcurrentOperationCount:2];
[self.queue addOperation:invocationOperation];
[self.queue addOperation:invocationOperation1];
3). GCD
- 操作使用Blocks定義;
- 隊(duì)列負(fù)責(zé)調(diào)度任務(wù)執(zhí)行所在的線程以及具體的執(zhí)行時(shí)間;
- 隊(duì)列的特點(diǎn)是先進(jìn)先出(FIFO)的,新添加至隊(duì)列的操作都會排在隊(duì)尾.
- 簡單用法:
dispatch_queue_t serialQueue = dispatch_queue_create("com.cc", nil);//串行分發(fā)隊(duì)列
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//并發(fā)分發(fā)隊(duì)列
dispatch_queue_t mainQueue = dispatch_get_main_queue();//主分發(fā)隊(duì)列 主線程
//dispatch_async異步執(zhí)行
dispatch_async(mainQueue, ^{
[NSThread sleepForTimeInterval:5];
});
//dispatch_sync阻塞執(zhí)行
dispatch_sync(mainQueue, ^{
[NSThread sleepForTimeInterval:5];
});//這樣會死鎖主線程 dispatch_sync等待block執(zhí)行完,block需要在主線程中運(yùn)行,相互死鎖
//2.gcd group用法
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, concurrentQueue, ^{
//
});
dispatch_group_async(group, concurrentQueue, ^{
});
dispatch_group_notify(group, mainQueue, ^{
//group執(zhí)行完后
});
- 其他用處:
信號量dispatch semaphore
dispatch_semaphore_create(1);//創(chuàng)建一個(gè)初始信號量為1的semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待信號量大于0,時(shí)間:永遠(yuǎn)
dispatch_semaphore_signal(semaphore);//釋放一個(gè)資源,使信號量加1
分發(fā)柵欄dispatch barrier
dispatch_barrier_async(queue, ^{
});//作用等待queue里面的操作完成后進(jìn)行block操作
分發(fā)源dispatch source
監(jiān)聽指定的各種事件
變量增加dispatch_source_type_data_add
變量OR dispatch_source_type_data_or
進(jìn)程相關(guān)dispatch_source_type_proc
文件讀寫
.......
4). 使用performSelecter
//在當(dāng)前線程運(yùn)行
[self performSelector:@selector(threadRun) withObject:nil afterDelay:1.0];
//在指定線程運(yùn)行
[self performSelector:@selector(threadRun) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];
//在后臺線程運(yùn)行
[self performSelectorInBackground:@selector(threadRun) withObject:nil];
//在主線程運(yùn)行
[self performSelectorOnMainThread:@selector(threadRun) withObject:nil waitUntilDone:YES];
5). 使用pthread創(chuàng)建線程
- (void)launchPthread{
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
}
}
void *PosixThreadMainRoutine(void * data){
NSLog(@"dosomething");
return NULL;
}
2. 線程數(shù)據(jù)安全
1). nonatomic atomic
使用atomic多線程原子性控制,atomic的原理給setter加上鎖,getter不會加鎖
@property (atomic,assign) NSInteger leftTicketsCount;
//默認(rèn)有10張票
self.leftTicketsCount=10;
//開啟多個(gè)線程,模擬售票員售票
self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread1.name=@"售票員A";
self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread2.name=@"售票員B";
self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread3.name=@"售票員C";
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
-(void)sellTickets
{
while (true) {
if (self.leftTicketsCount > 0 ) {
[NSThread sleepForTimeInterval:0.5];
self.leftTicketsCount--;
NSLog(@"thread:%@ ---> %ld",[[NSThread currentThread] name],self.leftTicketsCount);
}
else{
break;
}
}
}

讀取寫入并行發(fā)生的時(shí)候,會出現(xiàn)如上錯(cuò)誤
2). 使用GCD實(shí)現(xiàn)atomic操作:
給某字段的setter和getter方法加上同步隊(duì)列:
- (void)setCount:(NSInteger)newcount{
dispatch_sync(_synQueue, ^{
count = newcount;
});
}
- (NSInteger)count{
__block NSInteger localCount;
dispatch_sync(_synQueue, ^{
localCount = count;
});
return localCount;
}

3). 使用NSLock
_lock = [[NSLock alloc]init];
- (void)threadRunLock{
while (true) {
[_lock lock];
if (self.number > 0 ) {
[NSThread sleepForTimeInterval:0.5];
self.number --;
NSLog(@"thread:%@ ---> %ld",[[NSThread currentThread] name],self.number);
}
[_lock unlock];
}
}
相當(dāng)于給代碼片段加上lock了,所以依次輸出9-0
iOS系統(tǒng)提供了三種鎖
1.NSLock
2.NSConditionLock;條件鎖 --- 條件鎖是一個(gè)互斥鎖,可以通過特定值來鎖住和解鎖
3.NSRecursiveLock;遞歸鎖 --- 對同一線程,可以多次獲得(lock)而不會造成死鎖
在unix中,提供POSIX thread lock:
pthread_mutex_t mutex;//互斥鎖
pthread_rwlock_t lock;//讀寫鎖
pthread_condattr_t conLock;//條件鎖
點(diǎn)擊這里查看
4). 使用GCD的信號量和柵欄
在使用一些特殊三方庫的時(shí)候,例如七牛上傳,需要進(jìn)行異步并發(fā)操作,但是七牛自己會有一個(gè)下載隊(duì)列,并且開發(fā)者不能獲取到這個(gè)隊(duì)列,那么在我們需要設(shè)置自己的并發(fā)數(shù)就會有問題(...)
使用信號量可以很方便的解決該問題:
dispatch_semaphore_create(max);//創(chuàng)建一個(gè)初始信號量為max的semaphore
然后在隊(duì)列添加任務(wù)的時(shí)候
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待信號量大于0,時(shí)間:永遠(yuǎn)
有資源可以使用的時(shí)候往下繼續(xù)
addOpeartion...
在成功或者失敗返回的時(shí)候
dispatch_semaphore_signal(semaphore);//釋放一個(gè)資源,使信號量加1
欄柵:
在前面隊(duì)列執(zhí)行完成之后執(zhí)行該操作,簡單用法有點(diǎn)像讀寫鎖
總結(jié)
目前大概會用到的多線程除了pthread應(yīng)該都是必須掌握的,線程安全使用原子性(atomic)、NSLock、volatile和信號量比較常用