Thread Synchronization in c#

Thread Synchronization in c#

Thread synchronization in the C# programming language is an advanced concept or method of programming behavior. Thread synchronization in C# is used in multithreaded programming to coordinate or group multiple program threads and to manage direct access to available shared program resources in a secure order.

Thread Synchronization in c#

In a C# program, when multiple program threads run simultaneously, all available program threads can attempt to access or modify the same memory location, parameter variable, file, or data object at the same time. This can sometimes lead to false results and unpredictable program thread behavior.

Thread synchronization is a special feature of C#.

  • In a C# program, only one thread created must access essential code at a time.
  • Thread-shared data remains consistent across the created program threads.
  • User-defined program-created threads execute in a controlled proper order.

Why is thread synchronization needed in C#?

Analyze a shared variable in a C# program.

int test = 0;

Here, assume two threads execute.

test++;

The test++ increment operation here is not a single step. Internally, it works in several ways.

  • It reads the current value of test.
  • It increments the value of the test variable with each loop iteration condition update.
  • Finally, it stores the updated value in the test variable as a result.

In this concept, if two program threads execute these steps simultaneously, one program update could overwrite the other.

Here this problem is known as race condition.

Example of a race condition/synchronization (without synchronization) in a C#.

Using System;

using System.Threading;

class program

{

static int tester = 0;

static void Increase()

{

for (int p = 0; p < 50000; p++)

{

tester++;

}

}

static void Main()

{

Thread thrd1 = new Thread(Increase);

Thread thrd2 = new Thread(Increase);

thrd1.Start();

thrd2.Start();

thrd1.Join();

thrd2.Join();

Console.WriteLine(“The value of tester is = ” + tester);

}

}

race condition/synchronization explanation.

  • In this program, the thread synchronization process generates random thread outputs by checking the tester variable’s program value each time.
  • The tester output results in a value less than 100,000 because both user-created threads update the tester variable’s value simultaneously.

Solving the problem using the thread synchronization method.

Using locks in thread synchronization.

In a C# thread synchronization program, the lock statement allows only one thread to execute a block of program source code at a time.

Example of locks in thread synchronization.

using System;

using System.Threading;

class Program

{

static int tester = 0;

static readonly object lockElement = new object();

static void Increase()

{

for (int p = 0; p <= 50000; p++)

{

lock (lockElement)

{

tester++;

}

}

}

}

static void Main()

{

Thread thrd1 = new Thread(Increase);

Thread thrd2 = new Thread(Increase);

thrd1.Start();

thrd2.Start();

thrd1.Join();

thrd2.Join();

Console.WriteLine(“the result of tester is – ” + tester);

}

}

Locks in thread synchronization explanation.

  • In this program, the lock element locks the current thread object after running.
  • It outputs 100002 when it is locked. The resources stored in it are protected as shared resources.

How locks work in thread synchronization.

  • When a user-defined thread enters a locked program block,
  • it adopts a thread object lock condition.
  • Other system-local threads must wait here.
  • After the thread program executes, the lock created in the program is released.
  • After this, the second waited locked thread can enter the process.
  • This complete process guarantees a thread-safe execution process mechanism.

Essential Thread Synchronization Concept Behavior in C#.

Critical Thread Section.

A critical section is a portion of program source code where shared resources are accessed.

Example of a Critical Thread Section.

tester++;

This section must be synchronized within the thread.

Mutual Exclusion in Thread Synchronization.

In this case, only one thread can enter or deal with the critical section at a time.

Here it is known as mutual exclusion process.

Deadlock in Thread Synchronization.

A deadlock occurs in a thread synchronization event when two or more threads are constantly waiting on each other in a process.

Example of a deadlock in thread synchronization.

  • Here, thread 1 holds lock P, and the next process waits for lock Q.
  • Similarly, thread 2 holds lock Q, and waits for lock P, and both processes are locked.

Thread Synchronization Techniques in C# Methods.

lock in Thread Synchronization.

This is the simplest and most commonly used synchronization mechanism or method in thread synchronization.

lock(lockElement)

{

// Here we can define a critical section

}

Monitor in Thread Synchronization.

It provides advanced thread element object locking features in the thread synchronization process.

Methods of Monitor in Thread.

  • Enter()
  • Exit()
  • TryEnter()
  • Wait()
  • Pulse()

Example of Monitor in Thread Synchronization.

Monitor.Enter(lockElement);

try

{

tester++;

}

finally

{

Monitor.Exit(lockElement);

}

Mutex in Thread Synchronization.

It helps you synchronize between thread synchronization processes.

Mutex mutex = freshMutex();

mutex.WaitOne();

// Here we can define the critical mutex section

mutex.ReleaseMutex();

Semaphore in Thread Synchronization.

It helps you access a single resource simultaneously from multiple threads in a thread synchronization process.

Example of Semaphore Thread Synchronization.

If semaphore count = 2 is defined here, only two threads can access and manage the resource at a time.

AutoResetEvent in Thread Synchronization.

Automatically releases a waiting thread in the thread synchronization process.

ManualResetEvent in Thread Synchronization.

Releases all waiting threads until the thread synchronization process is manually reset.

Advantages of thread synchronization in C#.

  • It avoids race conditions in thread programs.
  • It maintains the consistency of program data across threads.
  • It securely holds shared resources used within threads.
  • It improves thread safety in the program.
  • It fixes the thread in the program, allowing you to know the behavior of the current thread in advance.

Disadvantages of thread synchronization in C#.

  • It creates performance overhead for the current program.
  • Multiple threads in the program have to repeatedly wait for the process to complete.
  • Any thread synchronization can generate many deadlocks.
  • Thread synchronization involves a complex and time-consuming debugging process.

A real-life example of thread synchronization.

Suppose you have a printer output device shared by multiple users on a local area network.

Here, without a synchronization process.

  • Here, multiple print jobs can be received simultaneously on the connected shared printer device.

Here, with a synchronization process.

  • The synchronization process here uses only one print job printer at a time, processing other requests one by one in a queue.
  • This is similar to the thread synchronization process in C# programming.

Thread Synchronization Summary in C#.

Thread synchronization in the C# programming language is used to manage and control multiple program threads accessing shared resources in a secure order. This avoids race conditions in the thread synchronization process and maintains data consistency within the program by allowing controlled thread execution activities to be completed within the current program.

Leave a Reply