Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# variable thread safety

A few questions about accessing a local variable from multiple threads at once:

  1. I have multiple threads writing and reading the value of a variable, should i synchronize access to it or not?

  2. The variable is being updated every few seconds from Thread1 and its being read and updated to the Database every few seconds from Thread2.

  3. Which problems can occur if i don't hold any logic and don't have any concurrency issues?

  4. Should i use volatile for this?

EDIT:

I would like to emphasize that i don't have any concurrency issues. Here's my specific scenarion:

a. My variable's name is pingLatency and it measures ping latency

b. Thread1 is sending a ping to 8.8.8.8 each 10 seconds and writes the latency to pingLatency

c. Thread2 updates a correcposing field with the value of pingLatency each 10 seconds.

d. Thread2 updates the same database row each time.

Now, i'm using this database field to monitor network connectivity. My question is - Can there be a situation where the variable is not updated or it would throw an exception due to thread safety issues? I want to avoid using lock because it just seems like an overkill.

What do you think?

like image 433
Uri Abramson Avatar asked Jul 31 '13 16:07

Uri Abramson


1 Answers

  1. Yes you should synchronize access to it, if it is a primitive type there are methods to do this for you without locks
  2. no comment
  3. not sure by what you mean by this... most likely you'll end up inserting the wrong value into the DB
  4. Don't use volatile, per Eric Lippert, it's overly complicated and the semantics are very weird.

Be careful of breaking the memory model, C# by and large follows most other languages in using sequential consistency for data-race-free programs (SC-DRF). Volatile breaks this, so just use locks to prevent a data race.

As for lock it's not as heavy as one might imagine, in most cases the lock won't be contended in the scenario you imagine. So acquiring the lock should be painless in most cases.

like image 70
Mgetz Avatar answered Oct 24 '22 21:10

Mgetz