Reputation: 2897
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?
Upvotes: 2
Views: 186
Reputation: 22290
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*/);
Upvotes: 2
Reputation: 2778
You might want to check sigwait. This method takes a set of signals and waits for the signals to arrive.
Upvotes: 1
Reputation: 9845
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.
Upvotes: 0