在Pharo中,有没有对应于Java的ThreadLocals的等价物,或者实现类似行为的方法?例如,在Hibernate中,ThreadLocals用于通过单个getCurrentSession方法调用提供一个线程(当前请求/上下文)工作实例的“作用域”统一-- Hibernate上的命名会话。开发人员不需要担心,只要相信该方法会返回正确的工作单元即可。在Pharo上这是可能的吗?
我在Pharo Books (Pharo by example,Pharo enterprise和Deep Pharo)和in this page上浏览了一下,但找不到有用的信息。
发布于 2017-02-27 23:35:49
在Pharo中,您使用ProcessLocalVariable的子类。例如:
"Create a class to store you variable"
ProcessLocalVariable subclass: #MyVariable.
"Use it like this"
MyVariable value: myValue.
"Inside your code, access to current value like this"
MyVariable value. 请注意,甚至比线程局部变量更强大的“动态变量”相对于执行堆栈(比线程更精确),您可以这样使用它:
"Create a class to store you variable"
DynamicVariable subclass: #MyVariable.
"Use it like this"
MyVariable
value: myValue
during: [
"... execute your code here... usually a message send"
self doMyCode ].
"Inside your code, access to current value like this"
MyVariable value. 这种类型的变量提供了相同的功能(它们甚至更强大),通常是最好的替代。
https://stackoverflow.com/questions/42489293
复制相似问题