Featured post
.net - multithreaded variable access -
this question keeps haunting me: in multithreaded/multiprocessor environment - necessary use explicit locks synchronize access shared variables?
here scenario: have global variable pointing shared object. when instance of object created, reference placed in variable , becomes accessible other threads/processors.
the object immutable - once created never changes, because of multiple threads can access without additional synchronization.
once in while need update object. creating new instance of object on side , place reference new object in global variable.
so here question: can consider replacing reference atomic operation. in other words variable have valid reference object - either old 1 or new one?
is necessary use explicit locks synchronize access shared variables?
necessary? no. idea? yes. low-lock techniques hard right , justified. remember, lock slow when contested; if locks being contested, fix problem causing them contested, rather going low-lock solution.
the object immutable - once created never changes, because of multiple threads can access without additional synchronization.
awesome.
once in while need update object. creating new instance of object on side , place reference new object in global variable.
so here question: can consider replacing reference atomic operation. in other words variable have valid reference object - either old 1 or new one?
yes. c# specification guarantees operations on references atomic. however atomicity 1 small part of thread safety. atomicity merely guarantees every time @ variable, valid reference out of it. it not guarantee every time @ variable current reference out of it. nor guarantee any 2 threads see same sequence of changes in same order. nor guarantee two atomic updates 2 different variables seen in order happened on every thread. atomicity guarantees practically nothing, , might not guarantee enough make program work way think should.
my advice: if can avoid accessing variable on multiple threads, so. if cannot avoid it, put locks around it. if find performance reasons locks slow , cannot eliminate enough contention should consider going dangerous low-lock techniques making variable volatile, using interlocked exchanges, , on.
- Get link
- X
- Other Apps
Comments
Post a Comment