使用字符串作为锁做线程同步

编程入门 行业动态 更新时间:2024-10-23 09:32:08
本文介绍了使用字符串作为锁做线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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();

此外,由于您的字符串不是 const 或 readonly,您可以更改它.所以(理论上)可以锁定你的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 ... } }

更多推荐

使用字符串作为锁做线程同步

本文发布于:2023-11-26 18:27:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!