Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string as a lock to do thread synchronization

While i was looking at some legacy application code i noticed it is using a string object to do thread synchronization. I'm trying to resolve some thread contention issues in this program and was wondering if this could lead so some strange situations. Any thoughts ?

private static string mutex= "ABC";  internal static void Foo(Rpc rpc) {     lock (mutex)     {         //do something     } } 
like image 482
Illuminati Avatar asked Nov 16 '10 10:11

Illuminati


People also ask

Can I lock string in C#?

Also, since your string is not const or readonly , you can change it. So (in theory) it is possible to lock on your mutex . Change mutex to another reference, and then enter a critical section because the lock uses another object/reference.

What is lock in synchronization?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

Can two threads acquire the same lock?

There is no such thing.


1 Answers

Strings like that (from the code) could be "interned". This means all instances of "ABC" point to the same object. Even across AppDomains you can point to the same object (thx Steven for the tip).

If you have a lot of string-mutexes, from different locations, but with the same text, they could all lock on the same object.

The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.

It's better to use:

 private static readonly object mutex = new object(); 

Also, since your string is not const or readonly, you can change it. So (in theory) it is possible to lock on your mutex. Change mutex to another reference, and then enter a critical section because the lock uses another object/reference. Example:

private static string mutex = "1"; private static string mutex2 = "1";  // for 'lock' mutex2 and mutex are the same  private static void CriticalButFlawedMethod() {     lock(mutex) {       mutex += "."; // Hey, now mutex points to another reference/object       // You are free to re-enter       ...     } } 
like image 194
GvS Avatar answered Sep 17 '22 13:09

GvS