程序员

iOS封装C语言P Thread

2018-12-04  本文已影响10人  小东邪啊

需求:iOS封装C语言P Thread以实现开始,结束,暂停,继续,指定线程名称,任务等的需求。


阅读前提:


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语言的方式创建一条线程

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 {

}

线程解析

4.停止线程

注意:停止线程时,我们必须先将该线程的任务停止下来,即使循环停止,所以在- (void)freeResource中我们先将_isStopBaseThread = true;

- (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让线程执行暂停与执行所对应的函数

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

上一篇 下一篇

猜你喜欢

热点阅读