From 3dc58c3a27b3c23123bb70a09348b1c38b8f77eb Mon Sep 17 00:00:00 2001 From: Nazanin Sabri Date: Sun, 5 Aug 2018 14:08:15 +0430 Subject: [PATCH] add lock --- Processes/lock.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 5 ++++ 2 files changed, 66 insertions(+) create mode 100644 Processes/lock.py diff --git a/Processes/lock.py b/Processes/lock.py new file mode 100644 index 0000000..afbe5cc --- /dev/null +++ b/Processes/lock.py @@ -0,0 +1,61 @@ +import time +import multiprocessing + +def deposit(balance): + for i in range(100): + time.sleep(0.01) + balance.value = balance.value + 1 + + +def withdraw(balance): + for i in range(100): + time.sleep(0.01) + balance.value = balance.value - 1 + +def problem(): + balance = multiprocessing.Value('i', 200) + d = multiprocessing.Process(target=deposit, args=(balance, )) + w = multiprocessing.Process(target=withdraw, args=(balance, )) + + d.start() + w.start() + + d.join() + w.join() + # it should print 200 but it does not + print("After transactions: ", balance.value) + + +def deposit_solution(balance, lock): + for i in range(100): + time.sleep(0.01) + lock.acquire() + balance.value = balance.value + 1 + lock.release() + + +def withdraw_solution(balance, lock): + for i in range(100): + time.sleep(0.01) + lock.acquire() + balance.value = balance.value - 1 + lock.release() + + +def solution(): + balance = multiprocessing.Value('i', 200) + lock = multiprocessing.Lock() + d = multiprocessing.Process(target=deposit_solution, args=(balance, lock)) + w = multiprocessing.Process(target=withdraw_solution, args=(balance, lock)) + + d.start() + w.start() + + d.join() + w.join() + # it should print 200 but it does not + print("After transactions: ", balance.value) + +if __name__ == '__main__': + problem() + solution() \ No newline at end of file diff --git a/README.md b/README.md index 102cfaa..37c4c5b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Python Multithreadig and Multiprocessing + +I've used this in the Wikipedia Crawler, check it out here or you can see the code in this repository.
+ + here are the resources I used: \ No newline at end of file