iOS封裝C語言P Thread

需求:iOS封裝C語言P Thread以實現開始,結束,暫停,繼續,指定線程名稱,任務等的需求。


閱讀前提:

  • 瞭解p thread基本用法
  • 瞭解iOS端線程基本概念
  • 瞭解線程加鎖基本原理

GitHub地址(附代碼) : 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語言的方式建立一條線程git

  • 第一個參數 : 建立的線程對象
  • 第二個參數 : 屬性,可填空
  • 第三個參數 : 該線程建立完成後觸發的方法(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;github

  • 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讓線程執行暫停與執行所對應的函數bash

  • 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便可看到控制檯上關於線程的打印,證實線程的功能已經實現完畢。post

- (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];
}

複製代碼
相關文章
相關標籤/搜索