進程能夠理解爲運行在系統的應用程序,進程之間是獨立的,一個進程能夠建立多個線程,提升工做效率,但會增長cpu的負荷。多線程
1,線程的建立:測試
方式1:比較少用atom
pthread_t thread;線程
pthread_create(&thread, NULL, run, NULL);orm
方式2:進程
NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"線程A"];資源
[thread start]get
方式3:it
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"建立完自動啓動"];form
方式4:隱式建立線程, 而且自動啓動
[self performSelectorInBackground:@selector(run:) withObject:@"隱式建立"];
2,線程共享資源的處理:
1,經過對代碼加互斥鎖,避免多線程訪問數據紊亂
@synchronized(self){
//代碼區
}
2,對屬性設置爲atomic,(通常設置爲nonatomic);測試有點問題。
3,線程間的通訊
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;