iOS-多线程之pthread

pthread简介

pthread是POSIX thread的简写,一套通用的多线程API,适用于Unix、Linux、Windows等系统,跨平台、可移植,使用难度大,C语言框架,线程生命周期由程序员管理。

方法列表

方法名 解释
pthread_create() 创建一个线程
pthread_exit() 终止当前线程
pthread_cancel() 中断另外一个线程的运行
pthread_join() 阻塞当前的线程,直到另外一个线程运行结束
pthread_attr_init() 初始化线程的属性
pthread_attr_setdetachstate() 设置脱离状态的属性(决定这个线程在终止时是否可以被结合)
pthread_attr_getdetachstate() 获取脱离状态的属性
pthread_attr_destroy() 删除线程的属性
pthread_kill() 向线程发送一个信号

使用

包含头文件#import <pthread.h>

- (void)test{
    //创建线程 定义一个pthread_t类型变量
    pthread_t thread;
    //开启线程执行任务
    //第一个参数&thread是线程对象,指向线程标识符的指针
	//第二个是线程属性,可赋值NULL
	//第三个run表示指向函数的指针(run对应函数里是需要在新线程中执行的任务)
	//第四个是运行函数的参数,可赋值NULL
    pthread_create(&thread,NULL,run,NULL);
    //设置子线程的状态设置为 detached,该线程运行结束后会自动释放所有资源
    pthread_detach(thread);
}

//新线程调用方法,里边为需要执行的任务
void * run(void *param){
    NSLog(@"%@", [NSThread currentThread]);
    return NULL;
}
发布了38 篇原创文章 · 获赞 5 · 访问量 9067

猜你喜欢

转载自blog.csdn.net/zj382561388/article/details/103126379