C# Solving A Thread Deadlock Tutorial - The EECS Blog

Skip to contentSearch for: SearchC# Solving a Thread DeadlockTslaPosted on February 9, 2020January 11, 20240C# Code Snippets Thread deadlock

About

In this code snippet, we will take a look at thread deadlocks in C# and how to resolve them.

If you see this post I made about thread resource locking you will see why a thread would need to lock a resource to prevent other threads from using it. But when you start locking down resources you could potentially run into a deadlock.

A thread deadlock occurs in such a situation:

    1. Thread 1 acquires a lock on resource A.
    2. Thread 2 acquires a lock on resource B.
    3. Thread 1 needs resource B to complete its execution.
    4. Thread 2 needs resource A to complete its execution.
    5. Both threads are now waiting on each other to finish.
C# thread deadlock diagram

To resolve this deadlock we need to change our code in such a way:

    1. Thread 1 acquires a lock on resource A.
    2. Thread 2 tries to acquire a lock on resource A but fails because it’s already locked.
    3. Thread 1 acquires a lock on resource B and completes its execution. After that, the lock on A and B is released.
    4. Thread 2 acquires a lock on A.
    5. Thread 2 acquires a lock on B and completes its execution.

Basically what you have to do is make sure that you are locking resources in the same order in all the threads. This way when the first common resource is locked by one thread no other thread can continue executing and locking on any other common resource required by the first thread.

Let’s have a look at the code below to see how to resolve a deadlock.

Code:

using System; using System.Threading; namespace ThreadDeadlock { class Program { static void Main(string[] args) { MyClass MC = new MyClass(); //Make threads. Thread th1 = new Thread(() => MC.transferFromAToB(100)); Thread th2 = new Thread(() => MC.transferFromBToA(100)); //Start threads. th1.Start(); th2.Start(); Console.ReadLine(); } } class MyClass { private int a; private int b; //lock objects. private Object aLock = new Object(); private Object bLock = new Object(); public MyClass() { a = 1000; b = 1000; } #region Deadlock Code public void transferFromAToB(int amount) { lock (aLock) { //Simulate computing time to get the value; Thread.Sleep(100); a = a - amount; lock (bLock) { //Simulate computing time to get the value; Thread.Sleep(100); b = b + amount; } } Console.WriteLine(amount + " was transfered from A to B."); } public void transferFromBToA(int amount) { lock (bLock) { //Simulate computing time to get the value; Thread.Sleep(100); b = b - amount; lock (aLock) { //Simulate computing time to get the value; Thread.Sleep(100); a = a + amount; } } Console.WriteLine(amount + " was transfered from B to A."); } #endregion #region Resolved deadlock Code /* public void transferFromAToB(int amount) { lock (aLock) { //Simulate computing time to get the value; Thread.Sleep(100); a = a - amount; lock (bLock) { //Simulate computing time to get the value; Thread.Sleep(100); b = b + amount; } } Console.WriteLine(amount + " was transfered from A to B."); } public void transferFromBToA(int amount) { lock (aLock) { //Simulate computing time to get the value; Thread.Sleep(100); a = a + amount; lock (bLock) { //Simulate computing time to get the value; Thread.Sleep(100); b = b - amount; } } Console.WriteLine(amount + " was transfered from B to A."); } */ #endregion } }

Resulting output:

c# thread deadlock resulting output
Thread deadlock
c# thread deadlock solved resulting output
Thread deadlock resolved

Related Posts:

  • C# Code Snippets Thread Synchronization with Monitor and Lock
    C# Threads And Resource Locking
  • C# Code Snippets Thread Join IsAlive Abort
    C# Thread Join, IsAlive, Abort
  • C# Code Snippets Mutex Semaphore Thread Signaling
    C# Mutex, Semaphore, Thread Signaling
  • C# Code Snippets Thread Pooling
    C# Thread Pooling
  • C# Code Snippets Sending and Receiving Data From a Thread
    C# Sending and Receiving Data From a Thread
  • C# Code Snippets threads and multithreading
    C# Threads and Multithreading
Categories: C# Computers ProgrammingTags: C#/ code snippets/ tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Comment *

Name

Website

The following GDPR rules must be read and accepted: I agreeThis form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Notify me of replies to my comments via e-mail.

Δ

Post navigation

« C# Threads And Resource LockingC# Thread Join, IsAlive, Abort »Search for: Search

Recent Posts

  • Interrupts And Timers
  • Watchdog Timer
  • ESP32 FreeRTOS Tutorial
the eecs blog online store white background

Follow us

Donate

Donate Crypto Here

Archives

Archives Select Month November 2025 September 2025 June 2025 December 2024 October 2024 September 2024 August 2024 June 2024 February 2024 January 2024 December 2023 November 2023 September 2023 August 2023 March 2023 February 2023 November 2022 September 2022 August 2022 February 2022 January 2022 December 2021 October 2021 September 2021 August 2021 July 2021 June 2021 September 2020 July 2020 June 2020 April 2020 March 2020 February 2020 January 2020 December 2019 November 2019 October 2019 September 2019 August 2019 July 2019 June 2019 May 2019 April 2019 March 2019 February 2019 January 2019

Categories

CategoriesSelect CategoryArduinoC#ComputersDigital ElectronicsElectronicsEmbedded SystemsFPGAJavascriptMicrocontrollersPHPProgrammingRaspberry PiRCRC HardwareRC SoftwareRepairReviewSecurity And Hacking

Tag » How To Avoid Deadlock In C#