线程本地、类实例本地存储?
是否有一种良好的、与平台无关的方法来实现线程和类实例本地的变量,即,如果您有 T 线程和 I 类实例,则您有该变量的 TxI 实例?我正在使用 D 编程语言版本 2,但一个与语言无关的良好答案也会很有用。
以下是一些限制:
- 决不能要求同步。这排除了将线程 ID 映射到作为成员变量的变量引用的哈希表。
- 不得保留应被垃圾收集的引用。这排除了由类实例索引的线程本地静态哈希表。
- 为了提高效率,初始化应该是惰性的。如果一个线程从不访问给定实例的变量,那么它永远不应该被创建。
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:
- Must never require synchronization. This rules out having a hash table mapping thread ID to variable reference as a member variable.
- Must not keep references around that should be garbage-collected. This rules out having a thread-local, static hash table indexed by class instance.
- Initialization should be lazy for efficiency. If a thread never accesses a given instance's variable then it should never be created.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用具有弱引用键的哈希表。不会阻止垃圾收集,并且会在收集键(类实例)时从哈希表中删除信息。
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.