Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Green thread in Ruby 1.9?

Ruby 1.9 uses native threads unlike Ruby 1.8 (MRI).

But is it possible to kindly ask Ruby 1.9.3 to create a green thread instead of a native one?

--

Why do I want that?

For testing purposes.

I'm trying to create a simple TCP server that would accept thousands concurrent connections that would sleep for a couple of seconds before returning some result.

In Ruby 1.8 I can easily create thousands of threads so the only limit for the number of concurrent connections is OS.

In Ruby 1.9 that seems to be impossible.

This code demonstrates what I mean:

require 'thread'

m = Mutex.new
c = 0
ta = Array.new 10000

ta.fill do
  Thread.new do
    m.synchronize { c += 1; p "created #{c}th" if c%100 == 0; }
    sleep 15
    m.synchronize { c -= 1; p "destroyed #{c+1}th" if c%100 == 0; }
  end
end

ta.each {|t| t.join}

It runs great in Ruby 1.8, but in 1.9 it's so miserable.

--

Unfortunately after some experimenting with eventmachine and its add_timer the best I could come up with was Node.js server:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  setTimeout(function() {res.end('Hello World\n');}, 10000 );
}).listen(8081, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8081/');

If anyone could demonstrate the same with EventMachine I would be glad to accept that answer.

like image 343
Oleg Mikheev Avatar asked Mar 17 '26 01:03

Oleg Mikheev


1 Answers

To put it short, the answer is no. The threading model in 1.9 now uses native threads and green threads are deprecated per se.

It would be helpful to hear exactly why you want to use green threads instead of OS-managed ones to suggest proper alternatives. Depending on your use case, you could look into using, for example, Proc objects with some kind of roll-your-own scheduling or Fibers as lightweight alternatives to native threads. You could also look into Thread / Fiber pooling if you find that the creation time of threads is a limiting factor.

like image 141
vaek Avatar answered Mar 19 '26 01:03

vaek