【问题标题】:Suspend main thread in C or infinity sleep在 C 或无限睡眠中挂起主线程
【发布时间】:2014-07-05 14:42:22
【问题描述】:

我希望我的线程永远运行。在代码中的某处,如果收到“BYE”,它将终止整个进程。当我使用 while(TRUE)for(;;) 时,我看到 CPU 使用率增加了 25%。睡眠功能也有限。有什么想法吗?

int _tmain(int argc, _TCHAR* argv[])
{
    // Run the Standard Input/Output to reply to the super application 
    // (interface probably written in C#)
    thread_standardIO_i = pthread_create(
        &thread_standardIO_thrd, 
        NULL, 
        stdio_thread, 
        NULL);

    while (1){
    }

    //sleep(9999999);

    return 0;
}

【问题讨论】:

  • “有限”对您意味着什么?为什么睡不着?
  • 如果您的输入/输出线程终止,首先就无法接收 BYE 命令,那么为什么不 (a) 直接加入该线程,或者更好的是 (b) 使 main线程输入/输出线程并在收到 BYE 时退出进程)。它实际上就像 invoking stdio_thread 一样简单,而不是旋转线程并尝试将“等待”范式串起来。
  • 可能是 POSIX pause()?
  • while (!sleep(999));将循环直到进程收到一个信号,该信号导致睡眠返回剩余的睡眠时间。
  • mjan635,当您“看到 CPU 使用率增加 25%”时;那是你所期望的吗?如果不是,您对 CPU 利用率的目标影响是什么?

标签: c multithreading sleep main


【解决方案1】:

为什么不只是 pthread_join 一些其他线程也将持续应用程序的生命周期,或者 pthread_cond_wait 一个从不发出信号的 condvar?这些操作将“永远”阻塞线程,不像sleep 只是要求它“在一段时间内”被唤醒。

【讨论】:

  • 由于可能的“虚假唤醒”pthread_cond_wait 也必须循环运行。
【解决方案2】:

在无限循环中使用睡眠,睡眠值有助于设置无限循环消耗的 CPU 使用率。

while(1)
{
sleep(1); // set sleep value as u wish
}

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2018-12-04
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2018-08-09
    相关资源
    最近更新 更多