Part 95 to 96 Deadlock in a multithreaded program

Part 95   Deadlock in a multithreaded program

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("main start");
            Account a1 = new Account(001,10000);
            Account a2 = new Account(002,20000);
            AccountManager m1 = new AccountManager(a1,a2,5000);
            Thread t1 = new Thread(m1.Transfer);
            t1.Name = "t1";
            AccountManager m2 = new AccountManager(a2, a1, 3000);
            Thread t2 = new Thread(m2.Transfer);
            t2.Name = "t2";
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            Console.WriteLine("main end");
        }
    }

    class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
        public Account(int id, double balance)
        {
            this.ID = id;
            this.Balance = balance;
        }
        public void WithDraw(double amount)
        {
            Balance -= amount;
        }
        public void Deposit(double amount)
        {
            Balance += amount;
        }
    }

    class AccountManager
    {
        public Account FromAccount { get; set; }
        public Account ToAccount { get; set; }
        public double AmountToTransfer { get; set; }
        public AccountManager(Account from,Account to,double amountToTransfer)
        {
            this.FromAccount = from;
            this.ToAccount = to;
            this.AmountToTransfer = amountToTransfer;
        }
        public void Transfer()
        {
            Console.WriteLine(Thread.CurrentThread.Name+"try to acquire lock on"+FromAccount.ID.ToString());
            lock (FromAccount)
            {
                Console.WriteLine(Thread.CurrentThread.Name+" acquired lock on "+FromAccount.ID.ToString());
                Console.WriteLine(Thread.CurrentThread.Name+" suspended for 1 second");
                Thread.Sleep(1000);
                Console.WriteLine(Thread.CurrentThread.Name+"back in action and try to acquire lock on" +ToAccount.ID.ToString());
                lock (ToAccount)
                {
                    Console.WriteLine("this code will not execute");
                    FromAccount.WithDraw(AmountToTransfer);
                    ToAccount.Deposit(AmountToTransfer);
                }
            }
        }

    }

Part 96   How to resolve a deadlock in a multithreaded program

static void Main(string[] args)
        {
            Console.WriteLine("main start");
            Account a1 = new Account(101,10000);
            Account a2 = new Account(102,20000);
            AccountManager m1 = new AccountManager(a1,a2,5000);
            Thread t1 = new Thread(m1.Transfer);
            t1.Name = "t1";
            AccountManager m2 = new AccountManager(a2, a1, 3000);
            Thread t2 = new Thread(m2.Transfer);
            t2.Name = "t2";
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            Console.WriteLine("main end");
        }
    }

    class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
        public Account(int id, double balance)
        {
            this.ID = id;
            this.Balance = balance;
        }
        public void WithDraw(double amount)
        {
            Balance -= amount;
        }
        public void Deposit(double amount)
        {
            Balance += amount;
        }
    }

    class AccountManager
    {
        public Account FromAccount { get; set; }
        public Account ToAccount { get; set; }
        public double AmountToTransfer { get; set; }
        public AccountManager(Account from,Account to,double amountToTransfer)
        {
            this.FromAccount = from;
            this.ToAccount = to;
            this.AmountToTransfer = amountToTransfer;
        }
        public void Transfer()
        {
            object _lock1, _lock2;
            if(FromAccount.ID<ToAccount.ID)
            {
                _lock1 = FromAccount;
                _lock2 = ToAccount;
            }
            else
            {
                _lock1 = ToAccount;
                _lock2 = FromAccount;
            }
            Console.WriteLine(Thread.CurrentThread.Name+"try to acquire lock on "+((Account)_lock1).ID.ToString());
            lock (_lock1)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " acquired lock on " + ((Account)_lock1).ID.ToString());
                Console.WriteLine(Thread.CurrentThread.Name+" suspended for 1 second");
                Thread.Sleep(1000);
                Console.WriteLine(Thread.CurrentThread.Name + "back in action and try to acquire lock on " + ((Account)_lock2).ID.ToString());
                lock (_lock2)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + " acquired lock on " + ((Account)_lock2).ID.ToString());
                    FromAccount.WithDraw(AmountToTransfer);
                    ToAccount.Deposit(AmountToTransfer);
                    Console.WriteLine(Thread.CurrentThread.Name+" Transferd "+AmountToTransfer.ToString()+" from "+FromAccount.ID.ToString()+" to "+ToAccount.ID.ToString());
                }
            }
        }

时间: 2024-11-10 18:12:19

Part 95 to 96 Deadlock in a multithreaded program的相关文章

Part 97 Performance of a multithreaded program

class Program { static void Main(string[] args) { Stopwatch s = new Stopwatch(); s.Start(); EvenNumbersSum(); OddNumbersSum(); s.Stop(); Console.WriteLine("before using multiple threads"+s.ElapsedMilliseconds); s = new Stopwatch(); s.Start(); Th

C# for Beginner Part 86 to 97

Part 86   Multithreading in C# What is a Process: Process is what the operatin system uses to facilitate(帮助) the execution of a program by providing the resources required.Each process has unique process Id associated with(关联) it. You can view the pr

【转】Multithreaded Python Tutorial with the “Threadworms” Demo

The code for this tutorial can be downloaded here: threadworms.py or from GitHub. This code works with Python 3 or Python 2, and you need Pygame installed as well in order to run it. Click the animated gif to view a larger version. This is a tutorial

95行代码实现最大熵模型训练

关于最大熵模型的介绍请看:http://www.cnblogs.com/hexinuaa/p/3353479.html 下面是GIS训练算法的python实现,代码不到100行. from collections import defaultdict import math class MaxEnt(object): def __init__(self): self.feats = defaultdict(int) self.trainset = [] self.labels = set() d

Timer.5 - Synchronising handlers in multithreaded programs

This tutorial demonstrates the use of the boost::asio::strand class to synchronise callback handlers in a multithreaded program. The previous four tutorials avoided the issue of handler synchronisation by calling the boost::asio::io_service::run() fu

Linux下的进程控制块——task_struct

在Linux中具体实现PCB的是 task_struct数据结构 我想说它真的很长很长...... ↓ 1 struct task_struct { 2 volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped *ruxia/ 3 void *stack; 4 atomic_t usage; 5 unsigned int flags; /* per process flags, defined below */ 6 unsigne

&lt;Linux内核源码&gt;内存管理模型

题外语:本人对linux内核的了解尚浅,如果有差池欢迎指正,也欢迎提问交流! 首先要理解一下每一个进程是如何维护自己独立的寻址空间的,我的电脑里呢是8G内存空间.了解过的朋友应该都知道这是虚拟内存技术解决的这个问题,然而再linux中具体是怎样的模型解决的操作系统的这个设计需求的呢,让我们从linux源码的片段开始看吧!(以下内核源码均来自fedora21 64位系统的fc-3.19.3版本内核) <include/linux/mm_type.h>中对于物理页面的定义struct page,也

解释清楚智能指针一【用自己的话,解释清楚】

写在前面 用自己的话解释清楚~ 智能指针是什么,可分为哪几种类型,各有什么特点,解决了什么问题,怎么解决的? 什么是智能指针? 智能指针是C++中的一个概念,主要是通过引用计数的方式,解决动态内存的自动释放问题(类似于Java .Python中的垃圾回收).主要解决程序常见的两个问题:动态的申请的内存没有释放:动态申请的内存释放后又被引用. 指针和引用的区别: 指针其实是一个变量,只不过它存储的是另一个变量的内存地址.而引用是另外一个变量的别名,它不占用空间.所以引用定义的时候必须初始化.引用访

Java+Windows+ffmpeg实现视频转换

最近由于项目需要,研究了一下如何用Java实现视频转换,“着实”废了点心思,整理整理,写出给自己备忘下. 思路 由于之前没有没法过相关功能的经验,一开始来真不知道从哪里入手.当然,这个解决,google一下立马就发现了ffmpeg,网上讲解用Java+ffmpeg来进行视频转换的文章也不在少数,我主要参考的这篇文章. 上文提到的这篇文章,基本已经把开发流程什么的讲的很清楚了,这里总结下: 1)核心是利用ffmpeg进行视频转换,我们自己并不写转换视频的代码,只是调用ffmpeg,它会帮我们完成视