Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between thread safe and async-signal safe

According to APUE 2e Chapter 12.5:

If a function is reentrant with respect to multiple threads, we say that it is thread-safe. This doesn't tell us, however, whether the function is reentrant with respect to signal handlers. We say that a function that is safe to be reentered from an asynchronous signal handler is async-signal safe.

My questions are

Q1:

Is there a "general re-entrant" concept (which means re-entrantcy in all circumstances)? If there is, does general re-entrant equal to re-entrant with respect to both multi-thread and async-signal only? Or is there also a third condition that has to be considered when talking about general re-entrant?

Q2:

Thread safety doesn't imply async-signal safety, which is obvious. But, does async-signal safety imply thread safety for sure? I googled a lot, people are saying that it does, but I can't find any source for it.

Q3:

If answers to both Q1 and Q2 are yes, I guess general re-entrant just equals to async-signal safe?

like image 762
PickBoy Avatar asked Mar 23 '12 10:03

PickBoy


1 Answers

Q1: async-signal safe is the strongest concept of reentrancy. It requires very careful use of resources and is hard to manage in cross-platform application code.

Q2: async-signal safe implies thread safe. Thread safe means it's OK to try calling the function twice, but from different threads; async-signal safe is stronger because two invocations of the function can be in the same thread. This makes things much harder, because you can't simply wait for the other invocation of the function to release its locks, the second call inside the signal handler has to be able to interrupt the first one even if shared resources are in an inconsistent state, then restore things when it exits. It's basically impossible to use shared resources/state from a signal handler: always use the "self-pipe trick" unless you really know how signal handlers work and have some obscure reason for writing insane code.

Q3: some people may use reentrant to mean just thread safe. Unix signal handlers are the only common place where anything stronger is needed, and that's a bit obscure because you shouldn't be trying to do anything clever there.

like image 195
Nicholas Wilson Avatar answered Sep 21 '22 16:09

Nicholas Wilson