使用字符串作为一个锁来做线程同步 [英] Using string as a lock to do thread synchronization

查看:81
本文介绍了使用字符串作为一个锁来做线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我一直在寻找一些遗留的应用程序code,我注意到它使用一个字符串对象做线程同步。我试图解决这个节目的一些线程争的问题,想知道,这可能会导致这样一些奇怪的情况。有什么想法吗 ?

 私有静态字符串互斥=ABC;内部静态无效美孚(RPC RPC)
{
    锁(互斥)
    {
        //做一点事
    }
}


解决方案

这样的字符串(从code)可能是的实习。这意味着ABC指向同一个对象的所有实例。甚至跨越的AppDomain 是你可以指向同一个对象(感谢史蒂芬为提示)。

如果你有大量的字符串互斥的,从不同的地点,但具有相同的文字,他们可能都锁定同一对象上。


  

实习生池节省字符串存储。如果您分配一个文字字符串常量几个变量,每个变量设置为引用同一个常数实习生池而不是引用具有相同值字符串的几个不同的实例。


这是更好地使用:

 私有静态只读对象互斥=新的对象();

此外,由于您的字符串不是常量只读,你可以改变它。这样(在理论上)能够锁定在您的互斥。改变互斥另一参考,而且由于锁使用另一个目的/参考然后输入一个临界区。例如:

 私有静态字符串互斥=1;
私人静态字符串互斥锁2 =1; //为'锁'互斥锁2和互斥量是相同的私有静态无效CriticalButFlawedMethod(){
    锁(互斥){
      互斥+ =。 //嘿嘿,现在互斥指向另一个参考/对象
      //你可以自由地重新进入
      ...
    }
}

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
    }
}

解决方案

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
      ...
    }
}

这篇关于使用字符串作为一个锁来做线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆