Are these thread-safe?
I attended an interview today in which the interviewer asked me the following question :
Is re-entrancy and mutual exclusion thread-safe ? Can you explain why ?
I am relatively new to concurrent p开发者_如何学Gorogramming and could not answer it.. But i said ...
Mutual exclusion is thread safe . But re-entrancy is not and that is the reason why we have re-entrant locks .
The interviewer moved on to the next question though to a different area ... I think i messed this one up ...
What is he expecting me to say when he asked me this ?
Proper answer should be:
Yes they are implementation of Thread safety.
re-entrancy
Writing code in such a way that it can be partially executed by one task, reentered by another task, and then resumed from the original task. This requires the saving of state information in variables local to each task, usually on its stack, instead of in static or global variables.
one example
Mutual exclusion
Access to shared data is serialized using mechanisms that ensure only one thread reads or writes the shared data at any time. Great care is required if a piece of code accesses multiple shared pieces of data—problems include race conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.
one example
Both are thread safe - you can read it also on Wikipedia:
http://en.wikipedia.org/wiki/Reentrant_(subroutine)
http://en.wikipedia.org/wiki/Mutual_exclusion
Re-entrant mutexes are mutexes that can be locked multiple times from the same thread if it is ensured that there's a corresponding unlock for each lock.
I quote http://en.wikipedia.org/wiki/Reentrant_(subroutine)
Both concepts of reentrancy and thread safety relate to the way functions handle resources. However, they are not the same.
While the concept of reentrancy can affect the external interface of a function, thread safety only concerns the implementation of the function and not its external interface.
-- In most cases, to make a non-reentrant function reentrant, its external interface must be modified such that all data is provided by the caller of the function.
-- To make a thread-unsafe function thread-safe, only the implementation needs to be changed, usually by adding synchronization blocks to protect shared resources from concurrent accesses by different threads.
Therefore, reentrancy is a more fundamental property than thread-safety and by definition, leads to thread-safety: Every reentrant function is thread-safe; however, not every thread-safe function is reentrant.
精彩评论