同步读写端口时避免递归?

Rebol 3中的所有端口操作都是异步的。我能找到的进行同步通信的唯一方法是调用 wait

但是在这种情况下调用 wait 的问题是,它将检查所有打开的端口的事件(即使它们不在传递给 wait 的端口块中)。然后它们调用响应的事件处理程序,但是可以在这些事件处理程序之一中执行读/写操作。这可能导致对“ wait”的递归调用。

我该怎么办?

3444 次浏览

You can just use a lock. Cummunication1 can set some global lock state i.e. with a variable (be sure that it's thread safe). locked = true. Then Communication2 can wait until it's unlocked.

loop do
sleep 10ms
break if not locked
end
locked = true
handle_communication()

in cases where there are only asynchronous events and we are in need on synchronous reply, start a timer or sleep for timeout, if the handler or required objective is met then say true, else false and make sure the event gets cancelled /reset for the same if critical.

Why don´t you create a kind of "Buffer" function to receive all messages from assyncronous entries and process them as FIFO (first-in, first-out)?

This way you may keep the Assync characteristics of your ports and process them in sync mode.

I think that there are 2 design problems (maybe intrinsic to the tools / solutions at hand).

  1. Wait is doing too much - it will check events for all open ports. In a sound environment, waiting should be implemented only where it is needed: per device, per port, per socket... Creating unnecessary inter-dependencies between shared resources cannot end well - especially knowing that shared resources (even without inter-dependencies) can create a lot of problems.

  2. The event handlers may do too much. An event handler should be as short as possible, and it should only handle the event. If is does more, then the handler is doing too much - especially if involves other shared resources. In many situations, the handler just saves the data which will be lost otherwise; and an asynchronous job will do the more complex things.