Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Race Conditions in Threading C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 591
    Comment on it

    Race condition is arise when multiple threads are accessing the shared data and they try to modify this shared data at the same time. The reason for arising a race condition is that we are unable to know the order of accessing a shared data among the multiple threads.

     

    Example:

    Let's take an example, we have two threads says t1,t2. These threads trying to access a shared variable y. Both of these two threads simultaneously need to read data from a variable y and then try to modify the data on the variable y. In this situation, value of shared variable will be  the last written value of the thread.


    See the below example to understand the race condition. In this example we are using a 3 threads which try to write a different different value to the variable lets take  x.

    using System;
    using System.Threading;
    namespace RaceConditionExample
        class ThreadProgram
        {
            int x = 0;
            void Thread1() { x = 1; }
            void Thread2() { x = 2; }
            void Thread3() { x = 3; }
            static void Main(string[] args)
            {
                ThreadProgram th = new ThreadProgram();
                Thread threads1 = new Thread(th.Thread1);
                Thread threads2 = new Thread(th.Thread2);
                Thread threads3 = new Thread(th.Thread3);
                threads1 .Start();
                threads2.Start();
                threads3.Start();
                Console.WriteLine(th.result);
                Console.Read();
            }
        }
    }
    

     

    Output:

     

     

     

    In the output of the above code we saw that the value of a variable x might be 1,2,3 or 0. This result is coming due to the operating system which decides the execution order of a threads as it will ignore the order in which we begins the threads execution. A thread which will execute after all others threads then that thread will have a least priority given by the operating system.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: