Code Visualizer | Python

Bank Multithreading Simulation

This code demonstrates a multithreading simulation of a bank class in Python, showcasing deposit and withdrawal methods through concurrent execution via threads and ensuring thread safety with locks.


Empty image or helper icon

Prompt

from random import randint
import threading
from time import sleep


class Bank():
    def __init__(self):
        self.balance = 0
        self.lock = threading.Lock()

    def deposit(self):
        for i in range(100):
            random_number = randint(50, 500)
            self.lock.acquire()
            self.balance += random_number
            if self.balance >= 500 and self.lock.locked():
                self.lock.release()

            print(f"Пополнение: {random_number}. Баланс: {self.balance}")


            sleep(0.001)

    def take(self):
        for i in range(100):
            random_number = randint(50, 500)
            print(f"Запрос на {random_number}")

            if random_number <= self.balance:
                self.balance -= random_number
                print(f"Снятие: {random_number}. Баланс: {self.balance}")
                sleep(0.001)
            elif random_number > self.balance:
                print("Запрос отклонён, недостаточно средств")
                self.lock.acquire()


            sleep(0.001)




bk = Bank()

# Т.к. методы принимают self, в потоки нужно передать сам объект класса Bank
th1 = threading.Thread(target=Bank.deposit, args=(bk,))
th2 = threading.Thread(target=Bank.take, args=(bk,))

th1.start()
th2.start()
th1.join()
th2.join()

print(f'Итоговый баланс: {bk.balance}')

Answer

Code Structure Overview

Imports

  • random.randint
  • threading
  • time.sleep

Class Definition: Bank

  • Attributes:
    • balance
    • lock
  • Methods:
    • __init__
    • deposit
    • take

Instantiation

  • bk = Bank()

Threads

  • Thread 1:
    • Target: Bank.deposit
    • Arguments: bk
  • Thread 2:
    • Target: Bank.take
    • Arguments: bk

Thread Execution

  • th1.start()
  • th2.start()
  • th1.join()
  • th2.join()

Final Output

  • Print final balance.

DOT Notation Visualization

digraph bank_code_structure {
    node [shape=box];

    subgraph cluster_imports {
        label = "Imports";
        randint;
        threading;
        sleep;
    }

    subgraph cluster_class_bank {
        label = "Class: Bank";
        balance [label="balance"];
        lock [label="lock"];
        
        "__init__()" -> balance;
        "__init__()" -> lock;
        
        deposit -> balance;
        deposit -> lock;
        take -> balance;
    }

    Bank [shape=ellipse];
    "__init__()" [label="__init__()", shape=ellipse];
    deposit [label="deposit()", shape=ellipse];
    take [label="take()", shape=ellipse];

    Bank -> "__init__()";
    Bank -> deposit;
    Bank -> take;
    
    bank_instance [label="bk = Bank()"];

    thread1 [label="th1 (Thread 1)", shape=ellipse];
    thread2 [label="th2 (Thread 2)", shape=ellipse];

    thread1 -> deposit;
    thread1 -> bank_instance;
    
    thread2 -> take;
    thread2 -> bank_instance;

    "th1.start()" -> thread1;
    "th2.start()" -> thread2;
    "th1.join()" -> thread1;
    "th2.join()" -> thread2;

    final_output [label="Final Balance Output", shape=ellipse];
    "Print Final Balance" -> final_output;
}

Explanation

Imports

  • The code imports necessary modules: randint from random, threading for multithreading, and sleep from time.

Bank Class

  • Defines a Bank class with balance and lock attributes initialized in the __init__ method.
  • deposit method increments balance by a random number within a locked context.
  • take method decrements balance if sufficient funds are available or triggers a lock if not.

Threads and Execution

  • Two threads are created to run deposit and take methods concurrently.
  • Methods are executed using start and synchronized using join.

Output

  • The final balance is printed after both threads complete execution.

For further learning and more complex scenarios, consider exploring relevant courses on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This code demonstrates a multithreading simulation of a bank class in Python, showcasing deposit and withdrawal methods through concurrent execution via threads and ensuring thread safety with locks.