【问题标题】:UNIX threads - about sleep and how to make a thread work for certain time?UNIX线程-关于睡眠以及如何使线程工作一段时间?
【发布时间】:2012-01-11 05:31:13
【问题描述】:

在 UNIX 中,如果一个线程调用 sleep 函数,那么整个进程在这段时间内不会做任何工作,还是只有调用 sleep 的线程在这段时间内不会做任何工作?

在多线程程序中,我想让一个线程工作一定时间,如何实现?

【问题讨论】:

  • 只有正在运行的线程进入睡眠状态

标签: multithreading unix operating-system


【解决方案1】:

男人睡觉说:

The sleep() function suspends execution of the calling thread until either seconds seconds have elapsed
or a signal is delivered to the thread and its action is to invoke a signal-catching function or to
terminate the thread or process.  System activity may lengthen the sleep by an indeterminate amount.

This function is implemented using nanosleep(2) by pausing for seconds seconds or until a signal
occurs.  Consequently, in this implementation, sleeping has no effect on the state of process timers,
and there is no special handling for SIGALRM.

所以“只有调用线程”。

至于您的第二个问题:这主要是您无法控制的,大多数人应该重新考虑他们的设计并将其留给操作系统——您的操作系统控制着线程的执行。您可以使用条件和信号来协调线程的操作在某种程度上。使用更少的线程和管理任务通常比直接使用线程更好/更容易。即使您想对其计时,也有很多工作要尝试在运行时计算出您的线程被分配了多少时间。

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多