Writing Thread Safe Code in C


In multi-threaded applications where multiple threads make call to the methods of a single object, it is necessary that those calls be synchronized. If code is not synchronized, then one thread might interrupt another thread and the object could be left in an invalid state. A class whose members are protected from such interruptions is called thread-safe.

Lock

Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread

namespace Monitor_Lock   
{   
    class Program   
    {   
        static readonly object _object = new object();   

        static void TestLock()   
        {   

            lock (_object)   
            {   
                Thread.Sleep(100);   
                Console.WriteLine(Environment.TickCount);   
            }   
        }   

        static void Main(string[] args)       
        {   
            for (int i = 0; i < 10; i++)   
            {   
                ThreadStart start = new ThreadStart(TestLock);   
                new Thread(start).Start();   
            }      
            Console.ReadLine();   
        }   
    }   
}

Here a static method "TestLock" that uses the lock statement on an object. When the method TestLock is called many times on new threads, each invocation of the method accesses the threading primitives implemented by the lock.

The Main method creates ten new threads and then calls Start on each one. The method TestLock is invoked ten times, but the tick count shows the protected method region is executed sequentially, about 100 milliseconds apart.

If another thread tries to enter a locked code, it will wait, block until the object is released.

Monitor

results matching ""

    No results matching ""