Task class in SVN
Last night I finished up support for the Task class, which will form a core part of the system.
The Task class provides essentially the same functionality as getcontext/setcontext and setjmp/longjmp in C, with a little more icing to make them more useful. The main functional difference is that when a new Task is created, it gets a new stack to operate on. This allows Tasks to be switched in and out with any other Task at any time.
The other main feature is the ability to associate a Task with a block. When the block is activated, it will begin executing the block.
You can probably see where this is going… thats right, greenthreads. Tasks are going to form the basis for green threading. The main thing that Threads add on top of Tasks is a scheduler, ie, which Task should run when.
Now, A small example:
ts = Task.current t2 = Task.new do puts "2: wee! new task! switching back.." t2.swap(ts) puts "2: you're returned!" end puts "1: activating new task.." ts.swap(t2) puts "1: back to the future!" ts.swap(t2) puts "1: and we're done."
Who’s output is:
1: activating new task.. 2: wee! new task! switching back.. 1: back to the future! 2: you're returned! 1: and we're done.
This is a trivial example, where
Task#new creates a new Task and associates the given block with this new task. But you can see how as Tasks are swapped back and forth, execution of the task continues exactly where left off.
I’m going to begin work on the Thread scheduler shortly, and I’m expecting to be able to implement it and the Thread class itself directly in Ruby (ie, no C).
The biggest thing missing is synchronization mechanisms. My plan is to add a Channel class which will allow for objects to be passed between Tasks, with some synchronization built-in.