[H-GEN] pthreads

Andrae Muys a.muys at mailbox.uq.edu.au
Thu Aug 26 02:43:07 EDT 1999


[ Humbug *General* list - semi-serious discussions about Humbug and
Unix-related topics. ]

On Thu, 26 Aug 1999, Byron Ellacott wrote:

> [ Humbug *General* list - semi-serious discussions about Humbug and
> Unix-related topics. ]
> 
> some_loop() {
> 	while (flag_signal == 0) {
> 		sleep(some_time);
> 	}
> 	/* do action appropriately here */
> }
> 
> or something similar.  In this context, unless multiple threads are calling 
> some_loop(), this code is entirely safe.  Should a strange system somehow 
> manage to do the flag_signal = 1 in a non-atomic way, (flag_signal == 0) 
> will still only fail once, and once only, even if it occurs in a non-atomic 
> way.

Note that if you are going to do it this way you should be declaring the
variable "volitile", otherwise the compiler just might optimise the loop
to while (1) { } which isn't what you wanted at all :).

Ok regarding the use of signal handlers in threaded programs:

The book I mentioned contains an entire chapter, appropriately placed in
the "Advanced Interfaces" section.  This is not a simple topic, and dosn't
have a simple answer.  (FWIW the use of fork() in a threaded program is
covered in the chapter "Advanced Topics"!)

Be aware that it isn't just pthread_* functions that aren't permitted in a
signal handler, but any async-unsafe function.  The book provides a list
of POSIX.1 async-safe functions -- they number 82 (and be careful, it
*dosn't* include exit()!!!)

	"In particular, an async-safe function can be interrupted at any
time by an asynchronous signal and can be re-entered by being called from
the signal handler.  They must either manipulate no memory that is common
between invocations, be atomic with respect to user programs, or they must
protect themselves from being reentered by masking signals while they are
manipulating global data."

Note that it is strongly advised that if you simply must use signals that
you have a single thread dedicated to recieving them and use normal
inter-thread communication calls to alert other threads of the signal.
(probably through a pthread_cond_signal()).

Andrae

--
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Andrae Muys              "Never ascribe to malice that which is adequately
andrae at humbug.org.au      explained by incompetence." - Napoleon Bonaparte


--
This is list (humbug) general handled by majordomo at lists.humbug.org.au .
Postings only from subscribed addresses of lists general or general-post.



More information about the General mailing list