"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

July 18, 2014

Multithreading - Automation Basics - Usage of lock to ensure threadsafe


Example Code
  • Usage of lock to ensure threadsafe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MultithreadedApp
{
    class Program
    {
        //static long _value1;
        private object threadLock = new object();
        void runcode()
        {
            lock (threadLock)
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("Value of _value1 " + i);
                }
            }
        }
        static void Main(string[] args)
        {
            Thread[] agents = new Thread[10];
            Program[] P = new Program[10];
            for (int i = 0; i < 10; i++)
            {
                P[i] = new Program();
                agents[i] = new Thread(P[i].runcode);
                agents[i].Start();
            }
            Console.ReadLine();
        }
    }
}
Happy Learning!!!

No comments: