mutex locks: should I lock out concurrent readers, or just writers?

  • Thread starter Thread starter Ken Overton
  • Start date Start date
K

Ken Overton

Or should I say, when I have data members that can be read from multiple
threads, should I put a lock around read-only access to those members in
addition to the write-accesses of those members? What if a reader attempts
to read the data while the writer is in the midst of writing to it?

Thanks,

-- kov
 
Ken Overton said:
Or should I say, when I have data members that can be read from multiple
threads, should I put a lock around read-only access to those members in
addition to the write-accesses of those members? What if a reader attempts
to read the data while the writer is in the midst of writing to it?

It depends on a few things, such as atomicity and whether you require
the absolute latest value. Personally, I would put a lock round it to
make sure you won't run into tricky situations, but in most simple
cases you'd *probably* get away without.

See http://www.pobox.com/~skeet/csharp/threads/volatility.shtml
 
Jon Skeet said:
It depends on a few things, such as atomicity and whether you require
the absolute latest value. Personally, I would put a lock round it to
make sure you won't run into tricky situations, but in most simple
cases you'd *probably* get away without.

Another alternative would be to use ReaderWriterLock. It's allegedly good on
performance, and allows you to keep constrain volatility to the usage you
require.
 
Back
Top