ios - 如何 "visualize"(观察)iOS 中退出的线程?

标签 ios multithreading runloop

在学习线程和运行循环时,我注意到一些文章说:“通常,线程一旦完成工作就退出。”所以有时有必要使用 NSRunloop 创建一个所谓的“不朽线程”(??我不知道确切的英文术语)。 .

问题是我如何证明“一旦完成工作就退出”这句话?我这样编码

- (void)doSomethingOnThread {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSLog(@"I'm on thread %@", [NSThread currentThread]);
//    });

    NSThread *thread1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"I'm on thread %@", [NSThread currentThread]);
    }];
    thread1.name = @"thread1";
    [thread1 start];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadExitHandler:) name:NSThreadWillExitNotification object:nil];
}

- (void)threadExitHandler:(NSNotification *)noti {
    NSLog(@"Thread will exit: %@", noti);
}

好吧,通知处理程序没有被调用。

所以,[1]:如何证明线程退出? [2]:什么样的线程会这样?(我知道主线程永远不会退出,那其他线程呢?GCD线程,例如?)

最佳答案

如果你想可视化它,我可能会使用调试器。例如,我在 NSThread 中设置了一个断点。子类,我看到 Xcode 左侧面板中列出的线程:

enter image description here

但是如果我在 main 之后一秒触发了另一个断点方法完成,我看到相关的“线程将退出”消息并且我的线程不再存在:

enter image description here

或者您可以添加 NSLog dealloc 中的声明您的NSThread 的方法子类,这也将证明它的释放。或者在调试内存对象图中查找子类。

Well, the notification handler is not called.



我建议您将您的观察员添加到 NSThreadWillExitNotification 在你开始你的线程之前。现在你在这个线程的开始和退出与观察者的添加之间有一个竞争条件。 FWIW,我确实看到了“线程将退出”消息。

无关,虽然学习线程和运行循环很好,但现在它几乎没有实际用途。掌握 GCD 可能更有用,它可以让我们摆脱线程的杂草,并提供性能优化和更丰富的 API 来编写健壮的多线程代码。

关于 GCD 是否创建持久线程,答案是肯定的,但是我们从这个细节中抽象出来了。但是 GCD 的性能优化之一是它为我们管理了一个线程“池”,而不是不断地启动新线程并为每个分派(dispatch)的代码块不断地销毁它们。

您可能想观看 WWDC 2016 的 Concurrent Programming With GCD in Swift 3 .它遍历队列、线程和运行循环之间的关系。

关于ios - 如何 "visualize"(观察)iOS 中退出的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240423/

相关文章:

ios - 带有名为 `imageView` 的 IBOutlet 的 UITableViewCell 与父类(super class) IBOutlet 冲突的错误

c++ - 使用 OpenCv 和多线程从 IP 摄像机获取实时视频

iphone - (iphone)如何在这里正确设置runloop?许多问题

sockets - CFWriteStreamScheduleWithRunLoop 有时有效,有时无效?

ios - 在 IOS 中移动到 View Controller 时出现问题

ios - 试图从 firebase Swift 获取数据

c - gethostbyname() 进程即使在不同的线程中也能一致地解析吗?

c++ - 不使用线程的c++ dll无限循环

iphone - 这里的 "Run Loop"到底是什么?

ios - 如何使用 Autolayout 为通用应用程序调整 UIView 的大小