A Tango Fibers question and a functional programming anecdote.

Mikola Lysenko mclysenk at mtu.edu
Mon Oct 29 12:00:27 PDT 2007


downs Wrote:

> Here's a question to the tango devs.
> I've been developing my own stackthreads (Fibers basically) library for
> a while now, and finally got it working a few days ago.
> 
> Then we did some speed tests and discovered that it was about twice as
> slow as Tango's Fiber implementation.
> 
> This prompted me to dig into the Fibers sourcecode, where I discovered
> that Fibers doesn't backup ECX/EDX on context switch, and the FP
> registers only on windows.
> 
> Now I am confused.
> 
> Could a knowledgeable tango dev kindly shed light on this issue? Why
> isn't it necessary to save all registers on a context switch?
> 

Well, as one of the culprits implicated in writing the fiber switching code, I might be able to explain things.  First, let me clear one thing up:  

Tango does not store the float registers on Windows.  Since the C calling convention on both Posix and Win32 states that the FPU is not preserved across calls, there is no need to do such a thing.  You may be confusing the floating point stack with the necromancy involving the FS segment values, which are part of the thread information block on windows.  Those values are necessary for unwinding the stack in the event of an exception and absolutely must be saved in that exact order.  Doing otherwise risks horrible disaster if the system were to inadvertently switch threads in the middle of a fiber switch or if one of the fibers were to generate an exception (via throw or otherwise).

Many things went in to making the fiber switching on Tango fast, including optimizing register usage and restructuring the API such that each operation could be performed in O(1) time with a low constant cost.  Seemingly simple stuff like marking/unmarking GC regions had to be overhauled from the Phobos' O(n) algorithm to make them efficient.

Even without optimizations, just getting fiber switching *right* is very difficult.  There are many subtle issues involving garbage collection, thread synchronization and exception handling.  I spent many hours hunting down tiny race conditions and testing various extreme cases in order to track down and exterminate as many bugs as we could possibly find.  

For these reasons and more, I would strongly recommend that you just use Tango's Fibers rather than try to roll your own.  They are highly optimized and have been rigorously checked.  While it is possible to get a fairly rudimentary version of context switching working, I can't say that I would trust such an implementation.

-Mik



More information about the Digitalmars-d mailing list