Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate with threads in Ruby?

I'm building a real time game, mostly chat based, and I need to have many of these chats running concurrently, receiving and sending data through web sockets.

I have been told that instead of spawning one process per game, I should have one process with one thread per game (maybe using Event Machine).

I'm using Juggernaut for the sockets part, it lets me send data to all the players in a game by using a publish/subscribe system: each player subscribes to one game. But how do I send data from each player to that particular game?

I was thinking that I could send the game ID or channel ID from the client to the server, and then send it to the corresponding thread.

But how do I send anything to a thread?

like image 392
HappyDeveloper Avatar asked Apr 06 '12 15:04

HappyDeveloper


People also ask

How do you use threads in Ruby?

But from Ruby 1.9 onwards, threading is performed by the operating system. The two threads running in the same Ruby application can never be truly concurrent. In Ruby, a multi-threaded program is created with the help of Thread class and a new thread is created by calling a block, i.e Thread. new.

Is multithreading possible in Ruby?

Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code.

How does Ruby handle concurrency?

In particular, Ruby concurrency is when two tasks can start, run, and complete in overlapping time periods. It doesn't necessarily mean, though, that they'll ever both be running at the same instant (e.g., multiple threads on a single-core machine).

What is thread join in Ruby?

Calling Thread. join blocks the current (main) thread. However not calling join results in all spawned threads to be killed when the main thread exits. How does one spawn persistent children threads in Ruby without blocking the main thread? Here's a typical use of join.


1 Answers

To send data to a thread, you can use Ruby Queue:

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/thread/rdoc/Queue.html

like image 200
joelparkerhenderson Avatar answered Sep 30 '22 05:09

joelparkerhenderson