9/11/13

Thread safe rotate index.

Sometimes you may need a rotation thread safe index.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Init value = Int32.MaxValue - 10");
            RotatorIndex.Init = Int32.MaxValue - 10;
            Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
            Thread thread2 = new Thread(new ThreadStart(ThreadMethod));
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();

            Console.WriteLine("Init value = - 10");

            RotatorIndex.Init = - 10;
            thread1 = new Thread(new ThreadStart(ThreadMethod));
            thread2 = new Thread(new ThreadStart(ThreadMethod));
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();

            Console.WriteLine("Init value = Int32.MinValue + 10");

            RotatorIndex.Init = Int32.MinValue + 10;
            thread1 = new Thread(new ThreadStart(ThreadMethod));
            thread2 = new Thread(new ThreadStart(ThreadMethod));
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();

            Console.ReadKey();
        }


        static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(RotatorIndex.ID);
            }
        }

        /// 








        /// This is a thread safe rotator index
        /// 
        class RotatorIndex
        {
            private static int _iSeq = 0;
            private static int _digits = 3;

            public static int Seq
            {
                get
                {
                    return Interlocked.Increment(ref _iSeq) & 0x7FFF % (int)Math.Pow(10,_digits);
                }
            }

            public static string ID
            {
                get
                {
                    return Seq.ToString().PadLeft(_digits,'0');
                }
            }            

            /// 
            /// Use it just for test
            /// 
            public static int Init
            {
                set
                {
                    _iSeq = value;
                }
            }
        }
    }
}