Skip to content

Commit

Permalink
add lock
Browse files Browse the repository at this point in the history
  • Loading branch information
nazaninsbr committed Aug 5, 2018
1 parent aa2b04a commit 3dc58c3
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Processes/lock.py
Original file line number Diff line number Diff line change
@@ -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()
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# Python Multithreadig and Multiprocessing


I've used this in the <a href="">Wikipedia Crawler</a>, check it out <a href="">here</a> or you can see the code in this repository.<br>


here are the resources I used:
<ul>
<li>https://www.youtube.com/playlist?list=PLeo1K3hjS3uub3PRhdoCTY8BxMKSW7RjN</li>
<li>https://dev.to/nbosco/multithreading-vs-multiprocessing-in-python--63j</li>
<li>https://tutorialedge.net/python/python-multithreading-tutorial/</li>
<li>http://www.bogotobogo.com/python/Multithread/python_multithreading_creating_threads.php</li>
<li>https://pymotw.com/2/multiprocessing/basics.html</li>
<li>https://www.youtube.com/watch?v=icE6PR19C0Y</li>
</ul>

0 comments on commit 3dc58c3

Please sign in to comment.