UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2010-03-03 10:30 PM

tomcio
Member
From: Poland
Registered: 2006-08-14
Posts: 113

Re: Canceling threads (pthread)

Hi!

I read few articles and manual pages about canceling threads in pthreads. In result I'm pretty confused...

So I can enable/disable and change cancellation type using:

pthread_setcancelstate ()
pthread_setcanceltype ()

I'm looking for way to guarantee, that part of code executed inside thread will not be interrupted by pthread_cancel () called in other thread. Sample function running ijn thread A:


pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, NULL);

// Section A1: Some code, which can be interrupted by pthread_cancel ()

pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &old_cancel_state);

// Section A2: This code have to be executed it cannot be interrupted by pthread_cancel ()

pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);

// Section A3: Again this code can be interrupted

Now, what will happen, when thread A will be executing code in section A2 and thread B will cancel thread A with pthread_cancel() ? I read, that pthread_cancel() will block until thread A will became cancelable again, is it true?

Offline

#2 2010-03-03 11:26 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,203

Re: Canceling threads (pthread)

See Michael's excellent pthread FAQ.

Although, having a quick look at it, it doesn't seem to handle thread
cancellation. Bummer. But yes, you seem to understand how it works.

(Using a mutex to protect your thread might be faster than this though,
so if changing cancel state takes too long you might want to switch.)

Offline

#3 2010-03-03 11:45 PM

tomcio
Member
From: Poland
Registered: 2006-08-14
Posts: 113

Re: Canceling threads (pthread)

You right, I will choose the simplest way and use mutex :)

Great FAQ btw, it explains many problems. It's better then manpages...

Offline

Board footer

Powered by FluxBB