Sloth多线程编程:GCD与NSOperationQueue应用

Sloth多线程编程:GCD与NSOperationQueue应用

【免费下载链接】Sloth Mac app that shows all open files, directories, sockets, pipes and devices in use by all running processes. Nice GUI for lsof. 【免费下载链接】Sloth 项目地址: https://gitcode.com/gh_mirrors/sl/Sloth

Sloth作为一款展示系统中所有打开文件、目录、套接字(Socket)、管道(Pipe)和设备的macOS应用,其核心功能依赖于高效的多线程处理。本文将深入分析Sloth中GCD(Grand Central Dispatch)与NSOperationQueue的应用实践,展示如何通过多线程技术提升应用性能与响应速度。

GCD在Sloth中的核心应用

GCD是Apple开发的多线程编程技术,通过调度队列实现任务的并行执行。在Sloth中,GCD被广泛用于处理耗时操作,确保UI界面的流畅响应。

后台执行lsof命令

Sloth的核心功能是通过执行lsof命令获取系统中所有进程打开的文件信息。这一操作耗时较长,因此被放在后台线程执行:

// [source/SlothController.m](https://link.gitcode.com/i/c55d3ec97fdc331f08c1f4f142e8a8c2)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    @autoreleasepool {
        int fileCount;
        LsofTask *task = [LsofTask new];
        NSMutableArray *items = [task launch:self->authRef numFiles:&fileCount];
        self.unfilteredContent = items;
        self.totalFileCount = fileCount;
        
        // 更新UI必须在主线程执行
        dispatch_async(dispatch_get_main_queue(), ^{
            self->isRefreshing = NO;
            // 重新启用控件
            [self->progressIndicator stopAnimation:self];
            [self->outlineView setEnabled:YES];
            [self->outlineView setAlphaValue:1.0];
            [self->refreshButton setEnabled:YES];
            [self->authenticateButton setEnabled:YES];
            // 过滤结果
            [self updateFiltering];
        });
    }
});

上述代码中,dispatch_asynclsof命令的执行放入全局高优先级队列,避免阻塞主线程。任务完成后,通过dispatch_async(dispatch_get_main_queue(), ^{...})将结果更新操作切换回主线程,确保UI操作的线程安全性。

线程安全的数据处理

Sloth中使用了多个GCD队列来确保数据处理的线程安全。例如,在处理文件过滤时,使用了主队列同步执行UI更新:

// [source/SlothController.m](https://link.gitcode.com/i/36c0cdbbf9631abed97bfc769fd912b3)
dispatch_async(dispatch_get_main_queue(), ^{
    [self updateFiltering];
});

NSTimer与定时任务

除了GCD,Sloth还使用NSTimer实现定期刷新功能,这是基于NSRunLoop的定时器机制,适用于需要定期执行的任务。

实现定期数据刷新

Sloth允许用户设置数据自动刷新间隔,这一功能通过NSTimer实现:

// [source/SlothController.m](https://link.gitcode.com/i/d0760dc00df809a964428889e41195d1)
updateTimer = [NSTimer scheduledTimerWithTimeInterval:secInterval
                                               target:self
                                             selector:@selector(refresh:)
                                             userInfo:nil
                                              repeats:YES];

上述代码创建了一个定时执行refresh:方法的定时器,时间间隔由用户偏好设置决定。当用户修改刷新间隔时,通过invalidate方法销毁旧定时器并创建新定时器:

// [source/SlothController.m](https://link.gitcode.com/i/f042b9e51d94272ea05de985c8a25635)
if (updateTimer) {
    [updateTimer invalidate];
    updateTimer = nil;
}

多线程同步与通信

Sloth在多线程编程中需要处理线程间的数据同步与通信,主要通过以下方式实现:

UI更新的线程限制

所有UI更新操作都被限制在主线程执行,例如进度指示器的启动与停止:

// [source/SlothController.m](https://link.gitcode.com/i/9857467ccd3b3984333e224c03665db8)
[progressIndicator startAnimation:self];

// [source/SlothController.m](https://link.gitcode.com/i/b80eb69f9ec9f0fdf350e81159d119a4)
[self->progressIndicator stopAnimation:self];

使用@autoreleasepool管理内存

在后台线程中,通过@autoreleasepool管理临时对象的内存,避免内存泄漏:

// [source/SlothController.m](https://link.gitcode.com/i/958fcbc1b09511799409a886a2186d0d)
@autoreleasepool {
    // 执行耗时操作
}

多线程性能优化策略

Sloth在多线程编程中采用了多种优化策略,确保应用在处理大量系统数据时仍能保持高性能。

优先级队列的使用

通过指定高优先级队列执行lsof命令,确保核心功能的响应速度:

// [source/SlothController.m](https://link.gitcode.com/i/f109bb519d9e4591dd610c9d684e0359)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    // 执行lsof命令
});

数据缓存与增量更新

Sloth维护了未过滤的原始数据缓存,避免重复执行lsof命令:

// [source/SlothController.m](https://link.gitcode.com/i/22c4cd63b397d5b31885c532b8fd3a65)
self.unfilteredContent = items;

在用户调整过滤条件时,直接使用缓存数据进行过滤,提高响应速度:

// [source/SlothController.m](https://link.gitcode.com/i/d2a7f326735ec0d32c558e18a056b735)
- (void)updateFiltering {
    // 使用self.unfilteredContent进行过滤
}

总结与最佳实践

Sloth通过GCD与NSTimer的结合使用,实现了高效的多线程处理。主要最佳实践包括:

  1. 耗时操作后台化:将lsof命令执行、数据解析等耗时操作放入GCD全局队列
  2. UI更新主线程化:所有UI操作通过dispatch_get_main_queue()确保在主线程执行
  3. 定时器任务管理:使用NSTimer实现定期刷新,并在不需要时及时销毁
  4. 内存管理优化:在后台线程使用@autoreleasepool管理内存
  5. 数据缓存策略:维护原始数据缓存,避免重复执行耗时操作

通过这些多线程技术的应用,Sloth能够在处理大量系统数据的同时保持UI的流畅响应,为用户提供高效的系统监控体验。Sloth的多线程实现代码主要集中在source/SlothController.m文件中,感兴趣的开发者可以深入阅读该文件,学习更多多线程编程技巧。

Sloth应用界面

注:上图为Sloth中使用的套接字(Socket)图标,Sloth通过多线程技术高效监控系统中的套接字连接状态。

Sloth的多线程架构为macOS应用开发提供了优秀的参考范例,展示了如何在复杂系统工具中平衡性能与用户体验。开发者可以通过阅读README.md了解更多关于Sloth的功能特性,或查看source/Util/目录下的工具类实现,深入学习多线程编程的细节处理。

【免费下载链接】Sloth Mac app that shows all open files, directories, sockets, pipes and devices in use by all running processes. Nice GUI for lsof. 【免费下载链接】Sloth 项目地址: https://gitcode.com/gh_mirrors/sl/Sloth

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值