iOS封裝C語言P Thread
需求:iOS封裝C語言P Thread以實現開始,結束,暫停,繼續,指定執行緒名稱,任務等的需求。
閱讀前提:
- 瞭解p thread基本用法
- 瞭解iOS端執行緒基本概念
- 瞭解執行緒加鎖基本原理
GitHub地址(附程式碼) :ofollow,noindex">iOS封裝C語言P Thread
簡書地址:iOS封裝C語言P Thread
部落格地址:iOS封裝C語言P Thread
掘金地址:iOS封裝C語言P Thread
一. 基類的寫法
1.所需變數
@interface XDXPThreadHandler () { pthread_t_baseThread;// 即我們主要控制的執行緒 bool_isStopBaseThread;// 是否停止執行緒的標誌 bool_isPauseBaseThread;// 是否暫停執行緒的標誌 pthread_mutex_t_baseThreadMutex;// 執行緒的鎖 pthread_cond_t_baseThreadCond;// 暫停與喚醒執行緒的變數 } @end
2.初始化
- (void)initBaseThread { _isStopBaseThread= false; _isPauseBaseThread = false; pthread_mutex_init(&_baseThreadMutex, NULL); pthread_cond_init(&_baseThreadCond, NULL); }
3.開啟執行緒
pthread_create 即為使用C語言的方式建立一條執行緒
- 第一個引數 : 建立的執行緒物件
- 第二個引數 : 屬性,可填空
- 第三個引數 : 該執行緒建立完成後觸發的方法(C語言的函式,非OC的方法),即該方法內即為在該執行緒內
- 第四個引數 : 向第三個方法中傳遞的引數(我們在這裡需要將該類的物件的例項傳過去,否則在函式內無法呼叫本類相關的方法和屬性)
int pthread_create(pthread_t * __restrict, const pthread_attr_t * _Nullable __restrict, void *(* _Nonnull)(void *), void * _Nullable __restrict);
- (void)startBaseThreadTask { [self initBaseThread]; pthread_create(&_baseThread, NULL, doBaseThreadTask, (__bridge_retained void *)self); log4cplus_error("XDXPThreadHandler", "%s - Start send BaseThread info thread !",ModuleName); } void * doBaseThreadTask(void *param);// 函式宣告 void * doBaseThreadTask(void *param) { XDXPThreadHandler *instance = (__bridge_transfer XDXPThreadHandler *)param; pthread_setname_np(instance.baseThreadName.UTF8String); while (instance->_isStopBaseThread == false) { if (true == instance->_isPauseBaseThread) { pthread_mutex_lock(&instance->_baseThreadMutex); pthread_cond_wait(&instance->_baseThreadCond,&instance->_baseThreadMutex); pthread_mutex_unlock(&instance->_baseThreadMutex); }else { [instance doBaseThreadTask]; usleep(XDXUSleepOneSec); } } return NULL; } - (void)doBaseThreadTask { }
- pthread_setname_np : 設定執行緒的名稱
執行緒解析
- 因為我們要模擬類似OC NSTimer每隔多少秒執行一次任務,即我們需要一個while迴圈不斷執行,執行一次sleep指定時間
- 其次我們需要通過是否停止flag來控制是否需要退出迴圈,好讓其他執行緒能夠銷燬掉此執行緒(呼叫pthread_join的原理為等執行緒結束任務後將執行緒殺掉)
- 如果需要暫停執行緒,我們需要藉助pthread_cond_wait函式來暫停執行緒,注意暫停恢復操作需要加鎖處理
- 如果不需要上述兩個flag我們則進行執行緒正常的操作,每隔指定秒數迴圈一次,這樣子類只需要重寫doBaseThreadTask即可使用該執行緒
4.停止執行緒
注意:停止執行緒時,我們必須先將該執行緒的任務停止下來,即使迴圈停止,所以在- (void)freeResource
中我們先將_isStopBaseThread = true;
- pthread_join : 即為等待執行緒任務結束後,殺死指定執行緒。 注意此函式只能在非自身執行緒執行!
-
_baseThread = NULL;
此操作必須在最後執行,否則無法執行pthread_join
函式
- (void)stopBaseThreadTaskThread { if (_baseThread) { log4cplus_error("XDXPThreadHandler", "%s - Stop send BaseThread thread !",ModuleName); [self freeResource]; }else { log4cplus_error("XDXPThreadHandler", "%s - Stop send BaseThread thread Failed, The base thread was destoryed!",ModuleName); } } - (void)freeResource { _isStopBaseThread = true; pthread_mutex_destroy(&_baseThreadMutex); pthread_cond_destroy(&_baseThreadCond); int err = pthread_join(_baseThread, NULL); if (err != 0) { log4cplus_error("XDXPThreadHandler", "%s - Destory send BaseThread thread faild. status : %d",ModuleName,err); }else { log4cplus_error("XDXPThreadHandler", "%s - Destory send BaseThread thread !",ModuleName); } _baseThread= NULL; _isStopBaseThread= false; _isPauseBaseThread = false; log4cplus_error("XDXPThreadHandler", "%s - Free send BaseThread info thread !",ModuleName); }
5.暫停與恢復執行緒
暫停與恢復執行緒的原理即利用_isPauseBaseThread
該flag讓執行緒執行暫停與執行所對應的函式
- pthread_cond_broadcast : 喚醒某條執行緒
- pthread_cond_wait : 使某條執行緒sleep
- (void)pauseBaseThread { if (_isPauseBaseThread == false) { pthread_mutex_lock(&_baseThreadMutex); _isPauseBaseThread = true; pthread_mutex_unlock(&_baseThreadMutex); log4cplus_info("Crop", "Suspend send BaseThread info Thread !"); }else { log4cplus_error("Crop", "The send BaseThread info thread had Suspend!"); } } - (void)continueBaseThread { if (_isPauseBaseThread == true) { pthread_mutex_lock(&_baseThreadMutex); _isPauseBaseThread = false; pthread_cond_broadcast(&_baseThreadCond); pthread_mutex_unlock(&_baseThreadMutex); log4cplus_info("Crop", "Resume send BaseThread info Thread !"); }else { log4cplus_error("Crop", "The send BaseThread info Thread is running!"); } }
二. 子類繼承基類
有了第一步中的操作,我們的父類執行緒已經寫好,子類只要繼承父類並實現- (void)doBaseThreadTask
即可做到每隔指定秒數完成某項任務
@interface XDXTestPThreadHandler : XDXPThreadHandler - (void)setBaseThreadName:(NSString *)name; @end @implementation XDXTestPThreadHandler - (void)doBaseThreadTask { [super doBaseThreadTask]; NSLog(@"Hello"); } @end
三. 程式中呼叫
我們在主程式中可以設定執行緒名稱以及執行緒每次等待時間等等,然後呼叫start,stop,pause,continue即可看到控制檯上關於執行緒的列印,證明執行緒的功能已經實現完畢。
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 非單例 self.testThread = [[XDXTestPThreadHandler alloc] init]; self.testThread.baseThreadName = @"World"; // 單例 self.testAThread= [XDXTestAPThreadHandler getInstance]; self.testAThread.baseThreadName = @"Hello"; } #pragma mark test - (IBAction)startBtnClicked:(id)sender { [self.testThread startBaseThreadTask]; }