www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Segmentation fualt on ubuntu linux when using Fiber

the following code use multi-threads to scheduler some fibers´╝î segfault
occur sometime!Is there anything wrong with the fiber's implementation.

private import core.thread;
private import std.stdio;

private class SyncQueue(T)
{

    private T[] queue;

    public synchronized void push(T o)
    {
        queue ~= o;
    }

    public synchronized T pop()
    {
        T o = null;
        if(queue.length > 1){
            o = queue[0];
            queue = queue[1..$];
        }
        else if (queue.length == 1)
        {
            o = queue[0];
            queue = [];
        }
        return o;
    }
}

private class Scheduler
{
    private SyncQueue!(Fiber) runQueue;
    public this ()
    {
        runQueue  = new SyncQueue!(Fiber);
    }

    public void addFiber(Fiber fiber)
    {
        runQueue.push(fiber);
    }

    public void run(int threadNum =1)
    {
        ThreadGroup tg = new ThreadGroup;
        for(int i =0;i<threadNum;i++){
          tg.create({
            while (true)
            {
                Fiber fiber = runQueue.pop();
                if (fiber is null)
                {
                   continue;
                }
                else
                {
                  fiber.call();
                  if (fiber.state != Fiber.State.TERM)
                     runQueue.push(fiber);
                }
            }
          });
        }
        tg.joinAll;
    }
}

class WorkFiber:Fiber
{
    this(){
        super(&run);
    }

    void run()
    {
        while (true)
        {
             writefln("Thread:%p,Fiber:%p",cast(void*)Thread.getThis,cast
(void*)Fiber.getThis);
             Fiber.yield();
        }
    }
}


void main()
{
    Scheduler p = new Scheduler;
    for(int i=0;i<30000;i++)
      p.addFiber(new WorkFiber);
    p.run(4);
}
May 17 2009