Pthread簡單使用
// 1. 創(chuàng)建線程對象
pthread_t thread;
// 2. 創(chuàng)建線程
/*
1>第一個(gè)參數(shù)
線程對象地址
2>第二個(gè)參數(shù)
線程屬性 不需要傳NULL
3>第三個(gè)參數(shù)
指向函數(shù)的指針
4>函數(shù)需要接受的參數(shù)
函數(shù)需要傳遞的參數(shù)
*/
pthread_create(&thread, NULL, task, NULL);
// 判斷兩條線程是否相等
pthread_equal(threadA, threadB);
void *task(void *param)
{
return NULL;
}
NSThread基本使用
//線程生命周期: 任務(wù)執(zhí)行完畢后釋放線程
// 創(chuàng)建線程(第一種)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(text:) object:@""];
// 線程優(yōu)先級(0~1)默認(rèn)0.5 只是提高調(diào)用概率 不是100%調(diào)用
thread.threadPriority
// 啟動線程
[thread start];
// 創(chuàng)建線程(第二種)
[NSThread detachNewThreadSelector:@selector(text:) toTarget:self withObject:@""];
// 創(chuàng)建線程(第三種)
[self performSelectorInBackground:@selector(text:) withObject:@""];
線程的狀態(tài)
// 創(chuàng)建線程后 處于新建線程狀態(tài)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(text:) object:@""];
// 開啟線程 線程會進(jìn)入"可調(diào)度線程池里"等待執(zhí)行 就緒<--->運(yùn)行
[thread start];
// 線程的阻塞狀態(tài)
[NSThread sleepUntilDate:<#(nonnull NSDate *)#>];
[NSThread sleepForTimeInterval:<#(NSTimeInterval)#>];
// 強(qiáng)制停止線程 線程死亡
[NSThread exit];
線程的安全
// 多個(gè)線程同時(shí)訪問一塊資源 會引發(fā)數(shù)據(jù)錯(cuò)亂或數(shù)據(jù)安全問題 (存取錢問題)
// 1. 互斥鎖 (會消耗大量CPU)
@synchronized (self) {
// 執(zhí)行代碼
}
// 原子屬性(atomic) 非原子屬性(nonatomic)
// atomic:會對屬性setter方法自動加鎖
線程間通訊
// 一個(gè)線程任務(wù)執(zhí)行完成后 轉(zhuǎn)到另一個(gè)線程執(zhí)行其他任務(wù)
// 回主線程執(zhí)行方法
[self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>]
// 到其他線程執(zhí)行方法
[self performSelector:<#(nonnull SEL)#> onThread:<#(nonnull NSThread *)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者