Can Ruby Fibers be Concurrent?

♀尐吖头ヾ 提交于 2019-12-04 07:59:48

问题


I'm trying to get some speed up in my program and I've been told that Ruby Fibers are faster than threads and can take advantage of multiple cores. I've looked around, but I just can't find how to actually run different fibers concurrently. With threads you can do this:

threads = []

threads << Thread.new {Do something}
threads << Thread.new {Do something}

threads.each {|thread| thread.join}

I can't see how to do something like this with fibers. All I can find is yield and resume which seems like just a bunch of starting and stopping between the fibers. Is there a way to do true concurrency with fibers?


回答1:


No, you cannot do concurrency with Fibers. Fibers simply aren't a concurrency construct, they are a control-flow construct, like Exceptions. That's the whole point of Fibers: they never run in parallel, they are cooperative and they are deterministic. Fibers are coroutines. (In fact, I never understood why they aren't simply called Coroutines.)

The only concurrency construct in Ruby is Thread.




回答2:


There seems to be a terminology issue between concurrency and parallelism.

I just can't find how to actually run different fibers concurrently.

I think you actually talk about parallelism, not about concurrency:

Concurrency is when two tasks can start, run, and complete in overlapping time periods. It doesn't necessarily mean they'll ever both be running at the same instant. Eg. multitasking on a single-core machine. Parallelism is when tasks literally run at the same time, eg. on a multicore processor

Quoting: Concurrency vs Parallelism - What is the difference?.

Also well illustrated here: http://concur.rspace.googlecode.com/hg/talk/concur.html#title-slide

So to answer the question:

Fibers are primitives for implementing light weight cooperative concurrency in Ruby.

http://www.ruby-doc.org/core-2.1.1/Fiber.html

Which doesn't mean it can run in parallel.




回答3:


if you want true concurrency you'll want to use threads with jruby (which doesn't actually have fibers, it only has threads, one per fiber).

Another option is to "fork" to new processes, which could run things in true parallel on MRI.



来源:https://stackoverflow.com/questions/3066392/can-ruby-fibers-be-concurrent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!