iOS中的多线程(关于Pthread)

1,353 阅读2分钟

「这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战

关于Pthread

Pthread简介

关于Pthread是一套通用的多线程的API,可以在Unix / Linux / Windows 等系统跨平台使用,使用C语言编写,需要程序员自己管理线程的生命周期,使用难度较大,开发中几乎不使用Pthread


Pthread使用方法

  • 使用Pthread,首先要包含头文件#import <pthread.h>

  • 创建线程,并开启线程执行任务

    - (void)click:(id)sender {
        //创建线程: 定义一个pthread_t类型变量
        pthread_t thread;
        pthread_t thread1;
        
        //开启线程: 执行任务
        pthread_create(&thread, NULL, run, NULL);
        pthread_create(&thread1, NULL, run, NULL);
        
        //设置子线程的状态设置为 detached,该线程运行结束后会自动释放所有资源
        pthread_detach(thread);
        pthread_detach(thread1);
    }
    
    void * run(void *param){
        NSLog(@"当前线程--%@",[NSThread currentThread]);
        for (NSInteger i = 0; i<5000; i++) {
            NSLog(@"-buttonClick-%ld-%@",(long)i,[NSThread currentThread]);
        }
        return NULL;
    }
    

    从代码中可以看出 Pthread 的创建执行其实也是比较简单的,不过实现过程是通过C语言进行的。

    pthread_create(&thread, NULL, run, NULL); 中各项参数含义:

    第一个参数 &thread 是线程对象,指向线程标识符的指针
    第二个参数是线程属性,可赋值 NULL
    第三个参数 run 表示一个C语言函数方法(就当于OC中绑定的执行方法)
    第四个是运行函数的参数,可赋值 NULL

    log:

    Snip20211103_22.png

    进程 ID:数字18070表示的是当前程序所处的进程ID
    线程 ID:数字17260331726032则表示当前所处的子线程ID
    线程标识:number 也可以作为线程的标识
    线程名字:上述代码没有给线程起名字,因此为 null

    所以可以通过线程ID进行判断是否成功开启了一个子线程


Pthread相关方法

  • 创建一个线程

    pthread_create()
    
  • 终止当前线程

    pthread_exit()
    
  • 中断另外一个线程的运行

    pthread_cancel()
    
  • 阻塞当前的线程,直到另外一个线程运行结束

    pthread_join()
    
  • 初始化线程的属性

    pthread_attr_init()
    
  • 设置脱离状态的属性(决定这个线程在终止时是否可以被结合)

    pthread_attr_setdetachstate()
    
  • 获取脱离状态的属性

    pthread_attr_getdetachstate()
    
  • 删除线程的属性

    pthread_attr_destroy()
    
  • 向线程发送一个信号

    pthread_kill()