【iOS】——NSThread

pthread

pthread介绍

pthread 是 POSIX(Portable Operating System Interface)线程库的缩写,它提供了一套跨平台的线程管理和同步的API,允许在包括iOS在内的多种操作系统上创建和管理线程。在iOS开发中,虽然更推荐使用Grand Central Dispatch (GCD) 或者Objective-C的@synchronizedNSOperationQueue等更高层次的API,但在某些需要底层控制的场景下,pthread仍然被广泛使用。

pthread的核心概念包括:

  • 线程创建:通过pthread_create函数创建一个新的线程。
  • 线程ID:每个线程都有一个唯一的标识符,类型为pthread_t
  • 线程结束:通过pthread_exit函数结束线程,或者主线程等待子线程结束使用pthread_join
  • 线程属性pthread_attr_t结构体用于设置线程属性,如堆栈大小、调度策略等。
  • 互斥锁pthread_mutex_t用于线程之间的同步,确保对共享资源的独占访问。
  • 条件变量pthread_cond_t用于线程间的同步,允许线程等待特定条件的发生。

pthread使用

//导入头文件
#import <pthread.h>
// 1. 创建线程: 定义一个pthread_t类型变量
pthread_t thread;
// 2. 开启线程: 执行任务
pthread_create(&thread, NULL, run, NULL);
// 3. 设置子线程的状态设置为 detached,该线程运行结束后会自动释放所有资源
pthread_detach(thread);

void * run(void *param)    // 新线程调用方法,里边为需要执行的任务
{
    NSLog(@"%@", [NSThread currentThread]);

    return NULL;
}

pthread的API

  • pthread_create(pthread_t _Nullable *restrict _Nonnull, const pthread_attr_t *restrict _Nullable, void * _Nullable (* _Nonnull)(void * _Nullable), void *restrict _Nullable); 创建一个线程
  • pthread_exit(void * _Nullable); 终止某个线程
  • pthread_cancel(pthread_t _Nonnull); 中断另一个线程的运行
  • pthread_join(pthread_t _Nonnull, void * _Nullable * _Nullable); 阻塞当前线程,直到另一个线程结束
  • pthread_attr_init(pthread_attr_t * _Nonnull); 初始化线程属性
  • pthread_attr_setdetachstate(pthread_attr_t * _Nonnull, int); 设置脱离状态的属性
  • pthread_attr_getdetachstate(const pthread_attr_t * _Nonnull, int * _Nonnull); 设置脱离状态的属性
  • pthread_attr_destroy(pthread_attr_t * _Nonnull); 删除线程的属性
  • pthread_kill(pthread_t _Nonnull, int); 向线程发送一个信号

NSThread

NSThread介绍

NSThread提供了一个面向对象的接口来创建和管理线程,相比底层的 pthreadNSThread 提供了更高级别的抽象,使得线程的创建和管理更加简单和安全。

一个NSThread对象代表一个线程,使用比较简单,但是需要手动管理线程的生命周期、处理线程同步等问题。

NSThread使用

创建、启动NSTread线程

使用 initWithTarget:selector:object: 或者 initWithBlock: 方法来创建 NSThread 实例

接着调用 start 方法来启动线程执行

  • 创建线程并手动启动线程
// NSThread 先创建线程,再启动线程
    // 1. 创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 2. 启动线程
    [thread start];    // 线程一启动,就会在线程thread中执行self的run方法

  • 创建线程并自动启动线程
// 创建线程后自动启动线程
    // 1. 创建线程
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

  • 隐藏式创建线程并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];

需要注意:block形式的创建方式 需在iOS10之后使用

NSThread线程属性

  • name属性:设置线程的名字。
NSThread *ThreadA = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    ThreadA.name = @"ThreadA";
    [ThreadA start];

  • qualityOfService属性:设置线程优先级。

该属性是一个枚举值,可供用户选择不同的优先级。

typedef NS_ENUM(NSInteger, NSQualityOfService) {

    // 用户交互级别,用于对用户界面有直接响应要求的任务。
    // 这种类型的任务需要立即执行,以保证良好的用户体验。
    NSQualityOfServiceUserInteractive = 0x21,

    // 用户发起级别,用于用户明确请求的任务,比如文件上传或下载。
    // 这些任务虽然重要,但是可以接受稍微的延迟。
    NSQualityOfServiceUserInitiated = 0x19,

    // 实用程序级别,用于后台非关键性任务,如日志记录或缓存更新。
    // 这些任务可以接受较大的延迟,因为它们不影响用户体验。
    NSQualityOfServiceUtility = 0x11,

    // 后台级别,用于完全不干扰用户操作的后台任务。
    // 这类任务可以接受最大的延迟。
    NSQualityOfServiceBackground = 0x09,

    // 默认级别,如果不确定任务的优先级,可以使用此值。
    // 系统会根据当前情况选择合适的服务质量等级。
    NSQualityOfServiceDefault = -1

} API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

NSQualityOfServiceUserInteractive优先级最高,从上到下依次降低,NSQualityOfServiceDefault为默认优先级。

  • callStackReturnAddressescallStackSymbols属性:

callStackReturnAddresses属性返回的就是该线程中函数调用的虚拟地址数组

callStackSymbols属性以符号的形式返回该线程调用函数

callStackReturnAddresscallStackSymbols这两个函数可以同NSLog联合使用来跟踪线程的函数调用情况,是编程调试的重要手段

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSThread *tempThread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
    tempThread.name = @"newThread";
    [tempThread start];
    
    NSLog(@"%@", NSThread.callStackReturnAddresses);
    NSLog(@"--------------------------");
    NSLog(@"%@", NSThread.callStackSymbols);
}

- (void)newThread {
    NSLog(@"%@", [NSThread currentThread]);
}

在这里插入图片描述

  • threadDictionary属性:

每个线程有自己的堆栈空间,线程内维护了一个键-值的字典,它可以在线程里面的任何地方被访问。你可以使用该字典来保存一些信息,这些信息在整个线程的执行过程中都保持不变。比如,你可以使用它来存储在你的整个线程过程中Run loop里面多次迭代的状态信息。

其他属性:
@property (class, readonly, strong) NSThread *mainThread; // 获取主线程
@property (class, readonly, strong) NSThread *currentThread;// 获取当前线程
@property NSUInteger stackSize; // 线程使用堆栈大小,默认512k
@property (readonly) BOOL isMainThread; // 是否是主线程
@property (class, readonly) BOOL isMainThread ; // 当前线程是否为主线程
@property (readonly, getter=isExecuting) BOOL executing ; // 线程是否正在执行
@property (readonly, getter=isFinished) BOOL finished ;  // 线程是否执行完毕
@property (readonly, getter=isCancelled) BOOL cancelled;  // 线程是否取消

NSThread提供的API

  • (NSThread *)mainThread;
    这是一个类方法,用于获取主线程(Main Thread)的NSThread对象。主线程是应用程序的主要执行线程,在该线程上执行UI操作和其他重要任务。
  • (BOOL)isMainThread;
    这是一个实例方法,用于判断当前线程是否为主线程。如果调用该方法的线程是主线程,则返回YES,否则返回NO。
  • BOOL)isMainThread;
    这是一个类方法,用于判断当前线程是否为主线程。与实例方法相似,但可以直接通过类名调用。
  • NSThread *current = [NSThread currentThread];这行代码获取当前线程的NSThread对象。可以使用这个对象来访问和操作当前线程的属性和方法。

  • (void)setName:(NSString *)name;
    这是一个实例方法,用于设置线程的名称。可以通过给线程设置一个有意义的名称来标识和识别线程。

  • (NSString *)name;
    这是一个实例方法,用于获取线程的名称。返回线程的名称字符串。

线程状态的控制方法

  • 启动线程

线程进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态

- (void)start;

  • 阻塞/暂停线程
+ (void)sleepUntilDate:(NSDate *)date; // 休眠到指定日期,线程会休眠直到达到指定的日期时间点后才会继续执行。
+ (void)sleepForTimeInterval:(NSTimeInterval)ti; // 休眠执行时常,线程会休眠指定的时间后再继续执行。

  • 取消线程
- (void)cancel ;
  • 退出线程
+ (void)exit;

线程间的通信

在开发中,我们有时需要在子线程进行耗时操作,操作结束后切换到主线程进行刷新UI。这就涉及到线程间的通信。

  • 在主线程上执行操作
// 在主线程上执行操作

//在主线程上执行指定的方法。参数 aSelector 是要执行的方法的选择器(方法名),arg 是传递给方法的对象参数,wait 表示是否等待执行完成后再返回。如果 wait 为 YES,则当前线程会等待执行完成后再继续,如果为 NO,则立即返回。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
//这个方法与前一个方法类似,但它还接受一个 modes 参数,用于指定执行方法的运行模式(Run Loop Modes)。modes 参数是一个字符串数组,用于指定运行模式的名称。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray<NSString *> *)array;

  • 在指定线程执行操作
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable 

  • 在当前线程执行操作
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

线程间的状态转换

线程间的转换通常指的是在不同线程之间迁移任务执行的上下文,特别是从后台线程切换到主线程,或者相反。由于 UI 更新必须在主线程上进行,而长时间运行的任务通常在后台线程执行以避免阻塞 UI

  • 新建一条线程后,线程进入新建态

  • 调用start方法启动线程后,线程会被加入到可调度线程池变为就绪态

  • 如果CPU现在调度当前线程对象,则当前线程对象进入运行状态,如果CPU调度其他线程对象,则当前线程对象回到就绪状态。

  • 如果CPU在运行当前线程对象的时候调用了sleep方法等待同步锁,则当前线程对象就进入了阻塞状态,等到sleep到时或者得到同步锁,则回到就绪状态。

  • 如果CPU在运行当前线程对象的时候线程任务执行完毕/异常退出,则当前线程对象进入死亡状态

在这里插入图片描述

  • 19
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值