Pharo Smalltalk 中的 ThreadLocal-like
ThreadLocal-like in Pharo Smalltalk
Pharo 中是否有 ThreadLocals 或 Java 的等价物,或实现类似行为的方法?例如,在 Hibernate 中,ThreadLocals 用于通过单个 getCurrentSession 方法调用提供一个线程(当前 request/context)"scoped" 工作实例的统一体——在 Hibernate 上命名为 Session。开发人员无需担心,只需相信该方法将 return 正确的工作单元即可。在 Pharo 上可以吗?
我在 Pharo Books(例如 Pharo、Pharo enterprise 和 Deep Pharo)和 in this page 上略读了此内容,但找不到有用的信息。
在 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.
请注意,与执行堆栈相关的 "dynamic variables" 比线程局部变量更强大(比线程更精确)
你这样使用它:
"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.
这种变量提供相同的功能(它们甚至更强大)并且通常是最好的替代品。
Pharo 中是否有 ThreadLocals 或 Java 的等价物,或实现类似行为的方法?例如,在 Hibernate 中,ThreadLocals 用于通过单个 getCurrentSession 方法调用提供一个线程(当前 request/context)"scoped" 工作实例的统一体——在 Hibernate 上命名为 Session。开发人员无需担心,只需相信该方法将 return 正确的工作单元即可。在 Pharo 上可以吗?
我在 Pharo Books(例如 Pharo、Pharo enterprise 和 Deep Pharo)和 in this page 上略读了此内容,但找不到有用的信息。
在 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.
请注意,与执行堆栈相关的 "dynamic variables" 比线程局部变量更强大(比线程更精确) 你这样使用它:
"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.
这种变量提供相同的功能(它们甚至更强大)并且通常是最好的替代品。