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

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

问题描述

在查看一些遗留应用程序代码时,我注意到它使用字符串对象进行线程同步.我正在尝试解决该程序中的一些线程争用问题,并且想知道这是否会导致一些奇怪的情况.有什么想法吗 ?

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

推荐答案

这样的字符串(来自代码)可能是实习".这意味着ABC"的所有实例都指向同一个对象.即使跨 AppDomains 你也可以指向同一个对象(感谢 Steven 的提示).

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.

实习生池保存字符串存储.如果将文字字符串常量分配给多个变量,则每个变量都设置为引用实习池中的相同常量,而不是引用具有相同值的多个不同 String 实例.

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.

最好用:

 private static readonly object mutex = new object();

此外,由于您的字符串不是 constreadonly,您可以更改它.所以(理论上)可以锁定你的mutex.将 mutex 更改为另一个引用,然后进入临界区,因为锁使用了另一个对象/引用.示例:

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天全站免登陆