What does Thread safe mean?

F

Frank Rizzo

Some of the classes in the framework are marked as thread-safe in the
documentation. In particular the docs say the following:
"Any public static (*Shared* in Visual Basic) members of this type are
thread safe. Any instance members are not guaranteed to be thread safe."

What exactly does this mean? Does this mean that if I call a shared
method from 2 different threads, nothing whacky will happen?
Also when it says that instance members are not guaranteed to be thread
safe, does that mean that I can't call an instance member from 2 threads
simultaneously?

In addition, the docs about the Queue class say the following:

"To guarantee the thread safety of the *Queue*, all operations must be
done through the wrapper returned by the Synchronized
<frlrfsystemcollectionsqueueclasssynchronizedtopic.htm> method."

Does this mean that I can call any member of the class from any number
of threads and have it be thread-safe? In other words, can I add/remove
objects to/from the queue from various threads and have everything be
hunky-dory?
 
N

Nicholas Paldino [.NET/C# MVP]

Frank,

See inline.
Some of the classes in the framework are marked as thread-safe in the
documentation. In particular the docs say the following:
"Any public static (*Shared* in Visual Basic) members of this type are
thread safe. Any instance members are not guaranteed to be thread safe."

What exactly does this mean? Does this mean that if I call a shared
method from 2 different threads, nothing whacky will happen?

Yes, that is exactly what it means.
Also when it says that instance members are not guaranteed to be thread
safe, does that mean that I can't call an instance member from 2 threads
simultaneously?

Well, you could, but you would get "wacky" results, as you say. They
were not coded with thread-safety in mind, and you would have to handle
access to those objects if you were to use them from separate threads.
In addition, the docs about the Queue class say the following:

"To guarantee the thread safety of the *Queue*, all operations must be
done through the wrapper returned by the Synchronized
<frlrfsystemcollectionsqueueclasssynchronizedtopic.htm> method."

Does this mean that I can call any member of the class from any number of
threads and have it be thread-safe? In other words, can I add/remove
objects to/from the queue from various threads and have everything be
hunky-dory?

Yes, but only if you get the wrapper that is returned from the
Synchronized method.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top