Thread Safety of basic value types

  • Thread starter Thread starter Etienne Boucher
  • Start date Start date
E

Etienne Boucher

String and all the integer value types smaller or equal to 32bit, as well as
Char and Enum types are marked as thread safe on MSDN. Does that mean I do
not need to protect them?

Etienne Boucher
 
Reading/writing those types is atomic, so you don't need to worry about
that. However things like "someInt++" (which is a read then a write) are not
atomic, and nor is anything involving more than one operation. So you might
need to have some sync code, depending on what your code does.

-Michael
MVP
 
Michael Giagnocavo said:
Reading/writing those types is atomic, so you don't need to worry about
that.

Atomicity isn't the only thing you need for thread-safe code though, of
course. If you want to make sure that the changes made on one thread
are visible on another, you need to have memory barriers (which are
automatically present using locking).

See http://www.pobox.com/~skeet/csharp/multithreading.html
 
Most of what I need to share directly is a state enum and a couple of
booleans, everything else will be synchronised through queues. Thanks a lot.

Just rhetorically... Would the pre-increment operator have more chance to be
done atomicaly? I read it is faster and preferable if the post-increment
property isn't used, at least in C++. It's what I use in all my for loops
now.

Etienne Boucher
 
Thanks alot too, that's a very good read. I'll make my couple of
cross-thread variables volatile.

Etienne Boucher
 
Just rhetorically... Would the pre-increment operator have more chance to
be
done atomicaly? I read it is faster and preferable if the post-increment
property isn't used, at least in C++. It's what I use in all my for loops
now.

As Jon Skeet has on his page, writing this kind of code is about eliminating
chance and luck. As far as perf, I doubt there's any difference, since the
JIT will probably fix it all up anyways.

Also, as Jon mentioned, there's more to it than atomicity: use volatile or
likewise (thanks Jon, great page!).

-mike
MVP
 
Yea, I've all that fixed up. Thanks alot to both of you.

Etienne Boucher
 

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

Back
Top