| amariano (4) | |||
|
Hi. I want to send a signal to a pthread so it can break the cycle it is performing.
However, I get the following error, which makes sense: file.c: In function ‘sig_func’: file.c:56:2: error: break statement not within loop or switch How can I code this differently to get the same result? | |||
|
Last edited on
|
|||
| kbw (5371) | |
| Use a condition variable and signal it that way. The worker will need to check the condition. | |
|
|
|
| amariano (4) | |
|
I am sorry, but I don't understand how can I use a condition variable to stop the thread of computing the function computing(). Please assume that function takes 1h to execute and I cannot modify it. | |
|
|
|
| kbw (5371) | |
|
If the worker thread is in a loop, then it should check if it needs to stop somewhere in the loop. That's where it check s the condvar. It's no different from any other loop processing, there's always check to determine whether you should continue or not. Anyway, that's how I'd aproach the problem. I found this FAQ that you might find useful. http://www.cognitus.net/html/howto/pthreadSemiFAQ_8.html | |
|
|
|
| Cubbi (1568) | |
|
The POSIX approach to stopping a thread is pthread_cancel(), not pthread_kill(). Don't forget to set PTHREAD_CANCEL_ASYNCHRONOUS (it is DEFERRED by default. | |
|
|
|
| amariano (4) | |
|
@kbw: But the loop has only ONE function, which I cannot re-write. I want to reset the thread when it is performing the computing() function! That's not a way to solve this... @Cubbi: I do not want to cancel any thread! pthread_kill is the primitive to send a signal. Did you look to the code? | |
|
|
|
| Cubbi (1568) | |
|
If you can modify pThread_func() and you can wait for computing() to return normally from one iteration, then go with what kbw is suggesting. If you cannot wait for computing(), then cancel. Signals aren't relevant: if your thread is inside some function, a signal handler cannot change that flow of execution. (Except on those platforms where it's possible to throw an exception from a signal handler, but that's very nonportable) | |
|
|
|
| amariano (4) | |
|
But Cubbi... That's exactly my problem! I want to stop the thread to execute the "computing()" function... I cannot cancel/kill it. This is an iterative algorithm, canceling and creating new threads is too much expensive. In a nutshell, I have to use the same thread (without killing it) but I cannot wait for it to finish. | |
|
|
|