Thread safe code is safe to call by concurrent threads. Reentrant code
is code that is safe to call while a previous call was interrupted, say
by a signal.
Here's an example of code that is thread safe but not reentrant:
int get_serial_number(void)
{
static mutex mymutex=PTHREAD_MUTEX_INITIALIZER;
static int myint=0;
int ret;
pthread_mutex_lock(&mymutex);
/* more code here */
ret=myint++;
/* more code here */
pthread_mutex_unlock(&mymutex);
return ret;
}
Without the mutex locks, it wouldn't be thread safe (as two calls could
return the same serial number). However, as it is this function is not
reentrant. If the code was interrupted and the function was called by
the same thread, the call to pthread_mutex_lock could self-deadlock.
DS
OK, so code may not be reentrant, but can be thread safe. Is it safe to
assume that reentrant code is thread safe?
--
Donald McLachlan E-mail Donald.M...@crc.ca
Communications Research Centre / RNS Tel (613) 998-2845
3701 Carling Ave., Fax (613) 998-9648
Ottawa, Ontario
K2H 8S2
Canada
I am not sure the above snipet is thread safe: the static int myint = 0
is of question. If it was a automatic stack variable then I would say it is
thread safe.
Thanx,
> OK, so code may not be reentrant, but can be thread safe. Is it safe to
> assume that reentrant code is thread safe?
Unfortunately, while this is usually true, it's not guaranteed.
Hardware memory visibility issues affect thread safety but don't affect
reentrancy. If the code is reentrant because it was written using good
design principles, it will be thread safe. But if it was made reentrant
using tricks (such as operations known to be atomic on the particular
platform) they may fail in an SMP/multithread situation. (Note that this
is not an issue on x86 platforms with any current hardware.)
DS
> I am not sure the above snipet is thread safe: the static int myint = 0
> is of question. If it was a automatic stack variable then I would say it is
> thread safe.
This is C code, not C++ code.
DS