线程本地、类实例本地存储?

发布于 2024-08-18 04:16:00 字数 288 浏览 3 评论 0原文

是否有一种良好的、与平台无关的方法来实现线程和类实例本地的变量,即,如果您有 T 线程和 I 类实例,则您有该变量的 TxI 实例?我正在使用 D 编程语言版本 2,但一个与语言无关的良好答案也会很有用。

以下是一些限制:

  1. 决不能要求同步。这排除了将线程 ID 映射到作为成员变量的变量引用的哈希表。
  2. 不得保留应被垃圾收集的引用。这排除了由类实例索引的线程本地静态哈希表。
  3. 为了提高效率,初始化应该是惰性的。如果一个线程从不访问给定实例的变量,那么它永远不应该被创建。

Is there a good, platform-agnostic way to implement a variable that's local to both a thread and a class instance, i.e. if you have T threads and I class instances, you have TxI instances of that variable? I'm using the D programming language, version 2, but a good language-agnostic answer would also be useful.

Here are some constraints:

  1. Must never require synchronization. This rules out having a hash table mapping thread ID to variable reference as a member variable.
  2. Must not keep references around that should be garbage-collected. This rules out having a thread-local, static hash table indexed by class instance.
  3. Initialization should be lazy for efficiency. If a thread never accesses a given instance's variable then it should never be created.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

煮酒 2024-08-25 04:16:00

不得保留应进行垃圾收集的引用。这排除了由类实例索引的线程本地静态哈希表。

使用具有弱引用键的哈希表。不会阻止垃圾收集,并且会在收集键(类实例)时从哈希表中删除信息。

Must not keep references around that should be garbage-collected. This rules out having a thread-local, static hash table indexed by class instance.

Use a hashtable with weak-referenced keys. Won't prevent garbage collection, and will drop the information from the hashtable when the key (the class instance) is collected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文