Why use threads in a Ruby Event Machine?

Since the event machine is called an event-based asynchronous I / O library (e.g. node.js), which is single-threaded and uses an event loop to process parallel requests, do you really need to take care and use (such as a rail controller when processing requests)?

I'm more used to the node.js model where you actually just complete your code inside a callback and then everything takes care of you. (the select () system call for kqueue, epoll, etc., which spawns new threads, is handled in the lower-level C ++ implementation), and ECMAscript, by its nature, has no threads anyway.

I recently saw this piece of ruby ​​code trying to learn about Event Machine:

Thread = Thread.current Thread.new{ EM.run{ thread.wakeup } } # pause until reactor starts Thread.stop 

I'm just wondering when threads should be used in the event-based programming paradigm in ruby ​​and what specific situation will require us to use.

I know that Ruby has threads built into the language (MRI green threads, JRuby JVM threads), so it might be tempting to use threads? However, from my point of view, these are various defeats of the whole goal, if you really should not worry about them in the application code of a higher level, since an event-based model is used to solve this problem.

Thanks. evaluate any answers / clarifications.

+4
source share
2 answers

When using EventMachine you cannot have a difficult task, because the time taken to complete your task is "selected" from the reactor, I use threads when I know that the task will be:

  • be blocked (you should never block the eventmachine thread)
  • use more cpu than my average tasks.

In these cases, spawning tasks in a separate thread allows him to do his job without interfering with the reactor doing his job.

Another option is to use fibers, which are another other animal.

+2
source

The biggest difference between a thread and a state machine, as far as I know, is that the threads will use a multi-core processor to perform the correct parallel processing, and the state machine processes everything in sequential order. On the other hand, it is easier for a state machine to maintain data integrity, since you do not need to worry so much about the state of the race.

+1
source

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


All Articles