Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Write a program that demonstrates thread cooperation. Suppose that you create and launch two threads, one deposits to an account, and the other withdraws from

Write a program that demonstrates thread cooperation. Suppose that you create and launch two threads, one deposits to an account, and the other withdraws from the same account. The second thread must wait to see if the amount to be withdrawn is more than the current balance in the account. Whenever new fund is deposited to the account, the first thread notifies the second thread to resume. If the amount is still not enough for a withdrawal, the second thread must continue to wait for more funds in the account. Assume the initial balance is 0 and the amount to deposit and to withdraw is randomly generated.
An example of the program is shown below:
import threading
import random
import time
class Account:
def __init__(self):
self.balance =0
self.condition = threading.Condition()
def deposit(self, amount):
with self.condition:
self.balance += amount
print(f"Thread 1: Deposit {amount}")
print(f"Balance: {self.balance}")
self.condition.notify()
def withdraw(self, amount):
with self.condition:
while self.balance amount:
print(f"Thread 2: Waiting for deposit")
self.condition.wait()
self.balance -= amount
print(f"Thread 2: Withdraw {amount}")
print(f"Balance: {self.balance}")
def depositor(account):
while True:
amount = random.randint(1,10)
account.deposit(amount)
time.sleep(random.randint(1,3))
def withdrawer(account):
while True:
amount = random.randint(1,10)
account.withdraw(amount)
time.sleep(random.randint(1,3))
account = Account()
t1= threading.Thread(target=depositor, args=(account,))
t2= threading.Thread(target=withdrawer, args=(account,))
t1.start()
t2.start()
OUTPUT: No "public class" found to execute
How do I fix this? please help.
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Databases On The Web Designing And Programming For Network Access

Authors: Patricia Ju

1st Edition

1558515100, 978-1558515109

More Books

Students also viewed these Databases questions