lolbert hoolagin
lolbert hoolagin

Reputation: 85

If I have 1 thread writing and 1 thread reading an int32, is it threadsafe?

I am using C#, and I need to know if having 1 thread reading, and 1 thread writing is safe without using any volatiles or locks. I would only be reading/writing to 32 bit ints and booleans.

Upvotes: 2

Views: 74

Answers (1)

Hans Passant
Hans Passant

Reputation: 942267

This is pretty much the definition of thread-unsafe code. If you analyze the need for a lock in threaded code then you always look for exactly this pattern. If you don't lock then the thread that reads will observe random changes to the variable, completely out of sync with its execution and at completely random times.

The only guarantee you get from the C# memory model is that an int and a bool update is atomic. An expensive word that means that you will not accidentally read a value where some of the bytes in the value have the new value and some have the old value. Which would produce a completely random number. Not every value update is atomic, long, double and structure types (including Nullable<> and decimal) are not atomic.

Not locking where necessary produces extremely hard to debug problems. They depend on timing and programs tend to settle into a execution patterns where timing doesn't vary much. But which suddenly can change, when the machine is occupied by another task for example. Your program could be running fine for a week, then fail once when you get an email message :) That is undebuggable.

Upvotes: 2

Related Questions