gpt4 book ai didi

ios - 线程和 isExecuting 变量

转载 作者:行者123 更新时间:2023-11-28 15:58:36 27 4
gpt4 key购买 nike

我试图弄清楚 IOs 如何管理线程:即使文档不建议同时使用 p_thread POSIX 和 NSThread(在 swift 中只是线程),我认为了解它们的工作方式很有帮助。我试图用 Thread 类进行测试,以了解 Apple 通过 Thread 类的“IsExecuting 变量”的意图。在其documentation Apple 声明此变量返回“如果接收方正在执行,则返回 true,否则返回 false”。因此,我尝试创建一个线程,打印它将进入休眠的时刻, sleep 5 秒,醒来,并打印它醒来并重复循环。

这是代码:

    func mythread() {
repeat{
print("myThread start to sleep ...")
Thread.sleep(forTimeInterval: 5)
print("...myThread wakes up")

}while(true)
}

还有另一个线程,每秒打印 mythread 的“isExecuting 变量”这是代码:

    func threadmonitor(){
repeat{
Thread.sleep(forTimeInterval: 1)
print(" myThread isExecuting? : \(myThread!.isExecuting)")
}while (true)
}

打印如下:

myThread start to sleep ...
myThread isExecuting? : true
myThread isExecuting? : true
myThread isExecuting? : true
myThread isExecuting? : true
...myThread wakes up
myThread start to sleep ...
myThread isExecuting? : true
myThread isExecuting? : true
myThread isExecuting? : true
myThread isExecuting? : true
myThread isExecuting? : true

为什么即使线程“MyThread”处于休眠状态,它的“isExecuting 变量”也打印为真?那么 Apple 的执行意图是什么?在这一点上,我不认为它打算线程在处理器中运行。

在这种情况下,它的意图是什么?

最佳答案

sleep 仍然算作执行。线程已经开始,还没有结束。

请注意,iOS 通常不通过 NSThread 管理其线程。它主要与队列(通过 NSOperationQueue 和 GCD)一起工作,这些队列建立在使用 pthreads 实现的线程之上。 NSThread 也是构建在 pthreads 之上,但如您所说,通常不鼓励使用它。

关于ios - 线程和 isExecuting 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403695/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com