Reader-Writer pattern (i.e. Interleave)

Topics: Samples and Patterns
Coordinator
Jan 8, 2007 at 4:21 AM
static void InterleaveTest()
{
    ThreadPool.SetMinThreads(6, 1000);
    Port<string> e0 = new Port<string>();
    Port<string> e1 = new Port<string>();
    Port<string> shutdown = new Port<string>();
    Port<string> c0 = new Port<string>();
    
    for (int i = 0; i < 10; i++)
    {
        e1.Push(i.ToString());
        e0.Push(i.ToString());
        c0.Push(i.ToString());
    }
 
    int activeExclusives = 0;
    int concurrent = 0;
 
    Selector.Activate(null,
        Selector.Interleave
        (
            // Shutdown.
            new SelectorGroup(Selector.SelectOne(false, shutdown,
                delegate(string s)
                {
                    Console.WriteLine("Shutdown: " + s);
                })),
 
            // Exclusive Group. Only 1 task will execute at a time - exclusive of all other selectors.
            new SelectorGroup
            (
                Selector.SelectOne(true, e0,
                    delegate(string s)
                    {
                        Interlocked.Increment(ref activeExclusives);
                        Console.WriteLine("Exclusive e0: {0} Active:{1}", s, activeExclusives);
                        Interlocked.Decrement(ref activeExclusives);
                    }),
                Selector.SelectOne(true, e1,
                    delegate(string s)
                    {
                        int i = Interlocked.Increment(ref activeExclusives);
                        Console.WriteLine("Exclusive e1: {0} Active:{1}", s, i);
                        Interlocked.Decrement(ref activeExclusives);
                    })
            ),
            // Concurent. Each selectors in this group can run concurrently.
            new SelectorGroup
            (
                Selector.SelectOne(true, false, c0,
                    delegate(string s)
                    {
                        Interlocked.Increment(ref concurrent);
                        Thread.Sleep(1);
                        Console.WriteLine("Concurrent: {0} tid:{1} active:{2}", s, Thread.CurrentThread.ManagedThreadId, concurrent);
                        Interlocked.Decrement(ref concurrent);
                    })
            )
        )
    );
    //shutdown.Push("stop");
}