Using XThreads to reduce memory overhead

Over the years I have been mostly ignorant of memory management in Ruby, given that most of the scripts I write are small. However, recently I have been writing scripts which persist as a service to other scripts, and which is where memory problems creep in.

To reduce the memory overhead, a thread can be used to contain just the code to be executed, and once execution has completed, that thread can be disgarded. The XThreads gem can be used for running jobs, and then removing the existence of the objects used in the jobs from memory.

In the following example XThreads is used to execute a shell command. Regardless of how much memory a shell command uses, it demonstrates how XThreads can be used.

require  'xthreads'

xthreads =

xthread = xthreads.create_thread('play') {`play -n synth 0.1 square 930 0.1 square 730 delay 0 .1 `}
xthreads['play'].state #=> :stop

Thread.list #=> [#<Thread:0xc33df8 run>, #<Thread:0xf75c78 sleep>] 

Thread.list #=> [#<Thread:0xc33df8 run>] 
xthreads['play'].state #=> :dead

When a new xthread is created, any dead threads are deleted.

01-11-2013 20:24