English 中文(简体)
无限循环,直到应用程序收到信号
原标题:Infinite Loop until application gets signal

我有一个启动5个线程的应用程序。

在启动这些线程之后,main()中什么都没有发生。

main(){
      `start thread 1..5
}

如何在main()中无限循环,使程序连续运行,直到得到信号。

我不想用

while(true)

因为它会吃掉CPU周期。(正如我所想)

Edit: I am using gcc 4 Thread Api :pthread OS : Linux

最佳回答

最简单的是:

while (true) sleep(1000);

最好是join()所有五个线程。

问题回答

sigsuspend()函数正是为了这个目的而设计的-它将挂起调用线程,直到它收到导致调用信号处理程序的信号。

为了避免出现争用情况(信号在进程调用<code>sigsuspend()</code>之前到达),您应该阻止信号,检查它,然后将掩码传递给<code>sigsuspend

/* Block SIGUSR1 */
sigset_t sigusr1set, origset;
sigemptyset(&sigusr1set);
sigaddset(&sigusr1set, SIGUSR1);
sigprocmask(SIG_BLOCK, &sigusr1set, &origset);

/* Set up threads etc here */

/* Unblock SIGUSR1 and wait */
sigdelset(&origset, SIGUSR1);
sigsuspend(&origset);

加入这些线程请参阅pthread_join

您可以尝试Boost::Synchronization函数,如下所示:

main(){
  `start thread 1..5
  wait for signal
  exit
}

Windows?使用WaitForMultipleObjects





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签