How to switch a Goliath or EventMachine context?

Suppose I have an I / O restriction operation. I have callbacks (or em-synchrony)

  • How does an EM switch to the next request while retaining the previous one waiting for a callback?
  • How to save Thread.current isolated variables?
  • How can I emulate lengthy work tasks?
+4
source share
1 answer

1. How does the EM switch to the next request while maintaining the previous pending callback?

In any reactor design, there is one thread of execution. So, only one can be performed at a time. If the reactor processes a request for this main thread, then no other request can intervene (joint scheduling). Now the request can β€œrefuse” control either voluntarily (in EM, we have EM.next_tick { # block } ), or by planning a future operation: a timer ( EM.add_timer { #block } ), or by performing another input operation -Output!

For example, if you use EM-Synchrony, then when you make an HTTP request (via em-http), then when the request is sent, the fiber pauses and a callback is created for you hood. When the request is completed, the callback is called by EventMachine through an internal callback .. and control returns to your request. For a deeper look: http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/

2. How to save the isolated variables of Thread.current?

No magic. In Ruby, we have local thread variables: Thread.current[:foo] = bar . Similarly, fiber has the same semantics, although what sometimes captures people is the same as the mechanism. Aka Thread.current[:foo] = bar .

See here: http://devblog.avdi.org/2012/02/02/ruby-thread-locals-are-also-fiber-local/

3. How can I emulate lengthy work tasks?

The best approach: take them outside the reactor. This applies to any reactor system.

a) Create a job queue and click on another process b) EM provides EM.defer , which spawns another thread.

Choose (a) when possible, over (b) .. you will thank yourself later.

+6
source

Source: https://habr.com/ru/post/1432033/


All Articles