views:

93

answers:

3

Hi

I have class A and classes B and C. class B runs one thread and class C runs n threads. class A should start the threads and than wait for a signal from the user (say Ctrl-c in Linux) - class A will stop all threads (of classes B and C), do some final work and the application will exit.

The question is: how should class A sleep until signal received? what is the best implementation?

A: 

Do some research on Spin locks. This is a pretty basic concurrency 101 question.

Also a bit broad without knowing what the other threads are doing.

Gandalf
From the question "class C runs n threads". This bit would put me off using spin locks unless the OP specified a value for n. If n is a large number then the spin locks could end up contending quite a lot. This has really bad implications for performance, as all the threads will consume CPU cycles while spinning and could starve the thread that's trying to get some work done. Using some kind of adaptive spin lock with a back off mechanism would mitigate this, but they're not always implemented for every platform.
Glen
+2  A: 

Sounds like a job for a condition variable. There's a tutorial on how to use pthreads condition variables here and another one on wikipedia here

The basic approcah is that all the threads that you want to kill periodically call pthread_cond_timedwait to check if a signal has been sent from class A.

In pseudocode each of your threads in classes B and C would look something like this

while (!pthread_cond_timedwait(/*some args (including a timeout)*/ ) {
    doSomeSmallUnitOfWork;
}

then in class A's signal handler that catches the CTRL-C (or whatever signal)

pthread_cont_signal(/*some more args*/);
Glen
It is unclear from the answer how class A should sleep until signal received. BTW, pthread_cond_signal() is not signal-safe function to be used in a signal handler.
Corwin
+1  A: 

You might want to check sigwait. This method takes a set of signals and waits for the signals to arrive.

hype