理发师问题与现实生活中的僵局

问题描述

我看到了以下有关如何防止死锁的片段。现在我的问题是,通过应用死锁预防或理发师问题,现实生活场景中的哪些流程将是有用的。 我的问题是,理论上我有点理解它,但我需要在现实生活中理解它,而不是理发师的问题。

我们每天使用哪些流程可以防止出现这 2 个同步问题。 我只想看看另一个例子,而不是理发师或餐饮问题。

    /**
      * Adapted from The Java Tutorial and converted to c#
     */

    /**
     * sample of how NOT to write multi-threaded programs.
    **/
    public class Deadlock
    {
        object resource1 = "resource1";
        object resource2 = "resource2";

        public static void DoWork()
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Working thread...");
                Thread.Sleep(100);
            }
        }

        public static void main(String[] args)
        {
            //These are the two resource 
            //we'll try to get locks for
            
            //first thread.
            //lock resource1 then resource2

            Thread t1 = new Thread(Deadlock.DoWork)
            {
                //Lock resource 1
                Console.WriteLine("Thread 1: locked resource 1");           
            //simulating some file I/O  
            //Basically,we just want to give the 
            //other thread a chance to run. Threads and deadlock
            //are asynchronous things
            //deadlock to happen here

           }
            void run()
            {
                
                    try
                    {
                     Thread.Sleep(100);
                    }
                    catch (Exception e) { }

               //Now wait 'till we can get a lock on resource 2
               DoWork();
               Console.WriteLine("Thread 1: locked resource 2");
               
                    
                }
        // second thread.  
        //It tries to lock resource2 then resource1
        Thread t2 = new Thread(Deadlock.DoWork)
        {
            //This thread locks resource 2 right away
            //Then it tries to lock resource1.  
             //Thread 1 locked resource1,and 
                //won't release it till it gets a lock on resource2.  
                //This thread holds the lock on resource2,and won't
                //release it till it gets resource1.  
                // Neither thread can run,//and the program freezes up.
                Deadlock.DoWork(resource1){

                 Console.WriteLine("Thread 2: locked resource 1");
              }
    
    };

    //Start the two threads. 
    //deadlock will occur,//and the program will enter an infinite loop.
    t1.start(); 
    t2.start();
  




      
       

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)