Break a look cycle within a phread

Hi.

I want to send a signal to a pthread so it can break the cycle it is performing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void sig_func(int sig)
{
 break ;
}

void *pThread_func(void *arg)
{
	signal(SIGSEGV,sig_func);

	while(1)
		while(1)
			computing();

}

int main(){

	createPthread();
	
        pthread_kill(thread,SIGSEGV);

}


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
Use a condition variable and signal it that way. The worker will need to check the condition.
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.
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
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.
@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?
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)
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.
Topic archived. No new replies allowed.