来晚了,但有一本电子书可以直接讨论Pharo中的这个问题,并提供了确切的解决方案。我知道它有效,因为我曾经使用过它。
https://books.pharo.org/booklet-ConcurrentProgramming/
这个解决方案直接来自于那本书,我并没有发明它。
解决方案涉及向类 BlockClosure 添加两个信息。
BlockClosure >> promise
^ self promiseAt: Processor activePriority
并且:
BlockClosure >> promiseAt: aPriority
"Answer a promise that represents the result of the receiver
execution
at the given priority."
| promise |
promise := Promise new.
[ promise value: self value ] forkAt: aPriority.
^ promise
创建一个 Promise 类。
Object subclass:
instanceVariableNames: 'valueProtectingSemaphore value hasValue'
classVariableNames: ''
package: 'Promise'
Promise >> initialize
super initialize.
valueProtectingSemaphore := Semaphore new.
hasValue := false
Promise >> hasValue
^ hasValue
Promise >> value
"Wait for a value and once it is available returns it"
valueProtectingSemaphore wait.
valueProtectingSemaphore signal. "To allow multiple requests for
the value."
^ value
Promise >> value: resultValue
value := resultValue.
hasValue := true.
valueProtectingSemaphore signal
我在实现MQTT数据读取器时使用了这个。我会向Broker请求最新的消息并返回一个Promise。这样我就可以循环使用Promise而不阻塞图像中运行的其他进程。
它的效果非常好。虽然我花了一些时间来理解它的工作原理,但并不难。
你可以通过将你的操作放在一个块中并发送给Promise方法来使用它。
myPromise := [broker readMessage ] promise.
你也可以进行测试:
(myPromise hasValue) ifTrue: [
myObject processMsg: (myPromise value)
]
你应该将任务放在自己的线程中,以防止阻塞图像的其余部分。