2016-12-30 27 views
0

我想弄清楚的IO如何管理线程:即使文档不建议同时使用p_thread POSIX和NSThread(斯威夫特只是线程),我认为它有助于了解他们工作。 我尝试使用Thread类进行测试,以了解Apple通过Thread类的“IsExecuting variable”所打算的内容。在其documentation Apple中声明,如果接收器正在执行,则此变量返回“true”,否则返回false。 所以我试图创建一个线程,打印它将进入睡眠,睡眠5秒钟,醒来,并打印它醒来,并重复周期的时刻。线程和isExecuting可变

这是代码:

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 variable”打印为真? 苹果计划通过执行来实现什么?在这一点上,我不相信它打算线程在处理器中运行。

在这种情况下

又有什么打算?

+1

他们不仅不建议这样做'p_thread'用'NSThread' /'Thread',与GCD的到来,他们建议你考虑完全放弃自己的线程编程。参见[并发编程指南:从主题客场迁移(https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091- CH105-SW1)。当然,如果你必须使用它,但GCD的生活比'NSThread'更容易。 – Rob

+0

在回答你的问题时,我相信它告诉你线程已经启动并且没有终止。 – Rob

回答

1

睡觉仍算在执行中。线程已经启动并且尚未完成。

注意,iOS版一般不会通过NSThread管理它的线程。它主要适用于队列(通过NSOperationQueue和GCD),它们构建在使用pthreads实现的线程之上。 NSThread也是构建在pthread之上,但是正如你所说,它的使用一般是不鼓励的。