Alex Rivera | Logout

Code Re-entrancy vs. Thread Safety

Asked 2008-12-09T10:45:35.627
26

What is the difference between the concepts of "Code Re-entrancy" and "Thread Safety"? As per the link mentioned below, a piece of code can be either of them, both of them or neither of them.

Reentrant and Thread safe code

I was not able to understand the explaination clearly. Help would be appreciated.

Edit
Report

1 Answer

9

That article says:

"a function can be either reentrant, thread-safe, both, or neither."

It also says:

"Non-reentrant functions are thread-unsafe".

I can see how this may cause a muddle. They mean that standard functions documented as not required to be re-entrant are also not required to be thread-safe, which is true of the POSIX libraries iirc (and POSIX declares it to be true of the ANSI/ISO libraries too, ISO having no concept of threads and hence no concept of thread-safety). In other words, "if a function says it is non-reentrant, then it is saying it's thread-unsafe too". That's not a logical necessity, it's just a convention.

Here's some pseudo-code which is thread-safe (well, there's plenty of opportunity for callbacks to create deadlocks due to locking inversion, but let's assume the documentation contains sufficient information for users to avoid that) but not re-entrant. It is supposed to increment the global counter, and perform the callback:

take_global_lock();
int i = get_global_counter();
do_callback(i);
set_global_counter(i+1);
release_global_lock();

If the callback calls this routine again, resulting in another callback, then both levels of callback will get the same parameter (which might be OK, depending on the API), but the counter will only be incremented once (which is almost certainly not the API you want, so it would have to be banned).

That's assuming the lock is recursive, of course. If the lock is non-recursive, then of course the code is non-reentrant anyway, since taking the lock the second time won't work.

Here's some pseudo-code which is "weakly re-entrant" but not thread-safe:

int i = get_global_counter();
do_callback(i);
set_global_counter(get_global_counter()+1);

Now it's fine to call the function from the callback, but it's not safe to call the function concurrently from different threads. It's also not saf

answered 2008-12-09T13:03:54.037

Your Answer