P
P
Pavel Padozhnikov2015-09-15 21:13:07
Programming
Pavel Padozhnikov, 2015-09-15 21:13:07

Can you help explain the program?

I read about a lot of threading in LUA, and came across a program that works, but I do not understand the intricacies of its actions.
*****************************************

function consumer ()
  while true do
    local x = receive();
    io.write(x, "\n");
  end;
end;

function receive ()
  local status, value = coroutine.resume(producer);
  return value;
end;

function send (x)
  coroutine.yield(x);
end;

producer = coroutine.create(
  function ()
    while true do
      local x = io.read();
      send(x);
    end;
  end);

consumer()

*****************************************
In this program, I do not understand how does the action happen when consumer () calls receive () after the producer is called and I don’t understand what is happening here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
angru, 2015-09-16
@PaveL152

https://ru.wikipedia.org/wiki/
Coroutine Actually, you have a coroutine as a producer, their peculiarity is that they can return control to the code that calls them at any time, while maintaining their state, and then you can call again this coroutine and it will continue execution from that point.
the algorithm is as follows (let's imagine that the code of the send and receive functions is located in the place where they are called, just to make me write less):
1. the consumer in the loop calls the "producer" coroutine
2. the producer receives the data
3. using yield returns the data to the consumer (it's like return, only with the ability to continue the execution of the coroutine from this point)
4. the consumer outputs the data and calls the coroutine again (step 1. because the infinite loop) from the place where it stopped (and there is also an infinite loop, step 2)

D
Denis, 2015-09-15
@prototype_denis

I don’t know Lua, but the principle is the same for many Japanese.
In a loop, we display the result of the receive function.
receive is the function where the closure(?) is performed. The closure, in turn, in the loop, sends the value of the x variable using the send function.

while (true) 
{
    while (true)
    {
        x = read();
        yield(x); // break;
    }
    write(x);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question