Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define threadsafe?

Threadsafe is a term that is thrown around documentation, however there is seldom an explanation of what it means, especially in a language that is understandable to someone learning threading for the first time.

So how do you explain Threadsafe code to someone new to threading? My ideas for options are the moment are:

  • Do you use a list of what makes code thread safe vs. thread unsafe
  • The book definition
  • A useful metaphor
like image 267
Robert MacLean Avatar asked Jan 04 '10 12:01

Robert MacLean


People also ask

What is considered thread-safe?

Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously. Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions.

How do you know if something is thread-safe?

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.

What is thread-safe with example?

When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on working on the same object, this process is called Thread-Safety.


1 Answers

Eric Lippert says:

When I'm asked "is this code thread safe?" I always have to push back and ask "what are the exact threading scenarios you are concerned about?" and "exactly what is correct behaviour of the object in every one of those scenarios?".

It is unhelpful to say that code is "thread safe" without somehow communicating what undesirable behaviors the utilized thread safety mechanisms do and do not prevent.

like image 138
MarkJ Avatar answered Oct 03 '22 02:10

MarkJ