Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# allow a null value to be locked?

C# doesn't allow locking on a null value. I suppose I could check whether the value is null or not before I lock it, but because I haven't locked it another thread could come along and make the value null! How can I avoid this race condition?

like image 673
Casebash Avatar asked Aug 29 '11 04:08

Casebash


People also ask

Why there is no string in C?

There is no string type in C . You have to use char arrays. By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.

Why C has no exception handling?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

What does C++ have that C doesnt?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language.

Why array bounds checking is not available in C?

This is due to the fact that C++ does not do bounds checking. Languages like Java and python have bounds checking so if you try to access an out of bounds element, they throw an error. C++ design principle was that it shouldn't be slower than the equivalent C code, and C doesn't do array bounds checking.


2 Answers

You cannot lock on a null value because the CLR has no place to attach the SyncBlock to, which is what allows the CLR to synchronize access to arbitrary objects via Monitor.Enter/Exit (which is what lock uses internally)

like image 59
Ana Betts Avatar answered Sep 27 '22 23:09

Ana Betts


Lock on a value that is never null, e.g.

Object _lockOnMe = new Object(); Object _iMightBeNull; public void DoSomeKungFu() {     if (_iMightBeNull == null) {         lock (_lockOnMe) {             if (_iMightBeNull == null) {                 _iMightBeNull = ...  whatever ...;             }         }     } } 

Also be careful to avoid this interesting race condition with double-checked locking: Memory Model Guarantees in Double-checked Locking

like image 23
Chris Shain Avatar answered Sep 27 '22 21:09

Chris Shain