Thread Codeverständnis



  • Kann mir mal einer erklären wo bei dem Code der Kontostand hier namentlich Balance gespeichert wird. Es werden 10 Threads gestartet und jeder hebt etwas ab. Initalisiert wird der Kontostand mit 1000. Aber wo werden die zwischenzeitlichen Werte gespeichert ?

    //statements_lock2.cs
    using System;
    using System.Threading;
    
    class Account
    {
        private Object thisLock = new Object();
        int balance;
        static int zaehler = 0; 
    
        Random r = new Random();
    
        public Account(int initial)
        {
            balance = initial;
        }
    
        int Withdraw(int amount)
        {
    
             //This condition will never be true unless the lock statement
             //is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
    
            }
    
             //Comment out the next line to see the effect of leaving out 
             //the lock keyword:
            lock (thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine(zaehler);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    zaehler++;
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }
    
        public void DoTransactions()
        {
            for (int i = 0; i < 5; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }
    
    class Test
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
        }
    }
    


  • Scheinbar greifen die Threads alle auf dasselbe balance zu. Und es gibt ja die Anweisung

    balance = balance - amount;
    


  • Damit hab ich mir die Erklärung schon selbst geliefert. Intressant wäre noch zu wissen was

    (new ThreadStart(acc.DoTransactions));
    

    macht. Es funktioniert nämlich auch ohne dieses

    new ThreadStart();
    


  • blurry333 schrieb:

    Es funktioniert nämlich auch ohne dieses

    new ThreadStart();
    

    In älteren C# Versionen nicht.
    Da musste man den delegate-Typ explizit "new-en".


Anmelden zum Antworten