Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3dc58c3

Browse files
add lock
1 parent aa2b04a commit 3dc58c3

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

‎Processes/lock.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import time
2+
import multiprocessing
3+
4+
def deposit(balance):
5+
for i in range(100):
6+
time.sleep(0.01)
7+
balance.value = balance.value + 1
8+
9+
10+
def withdraw(balance):
11+
for i in range(100):
12+
time.sleep(0.01)
13+
balance.value = balance.value - 1
14+
15+
def problem():
16+
balance = multiprocessing.Value('i', 200)
17+
d = multiprocessing.Process(target=deposit, args=(balance, ))
18+
w = multiprocessing.Process(target=withdraw, args=(balance, ))
19+
20+
d.start()
21+
w.start()
22+
23+
d.join()
24+
w.join()
25+
# it should print 200 but it does not
26+
print("After transactions: ", balance.value)
27+
28+
29+
def deposit_solution(balance, lock):
30+
for i in range(100):
31+
time.sleep(0.01)
32+
lock.acquire()
33+
balance.value = balance.value + 1
34+
lock.release()
35+
36+
37+
def withdraw_solution(balance, lock):
38+
for i in range(100):
39+
time.sleep(0.01)
40+
lock.acquire()
41+
balance.value = balance.value - 1
42+
lock.release()
43+
44+
45+
def solution():
46+
balance = multiprocessing.Value('i', 200)
47+
lock = multiprocessing.Lock()
48+
d = multiprocessing.Process(target=deposit_solution, args=(balance, lock))
49+
w = multiprocessing.Process(target=withdraw_solution, args=(balance, lock))
50+
51+
d.start()
52+
w.start()
53+
54+
d.join()
55+
w.join()
56+
# it should print 200 but it does not
57+
print("After transactions: ", balance.value)
58+
59+
if __name__ == '__main__':
60+
problem()
61+
solution()

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
# Python Multithreadig and Multiprocessing
22

3+
4+
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>
5+
6+
37
here are the resources I used:
48
<ul>
59
<li>https://www.youtube.com/playlist?list=PLeo1K3hjS3uub3PRhdoCTY8BxMKSW7RjN</li>
610
<li>https://dev.to/nbosco/multithreading-vs-multiprocessing-in-python--63j</li>
711
<li>https://tutorialedge.net/python/python-multithreading-tutorial/</li>
812
<li>http://www.bogotobogo.com/python/Multithread/python_multithreading_creating_threads.php</li>
913
<li>https://pymotw.com/2/multiprocessing/basics.html</li>
14+
<li>https://www.youtube.com/watch?v=icE6PR19C0Y</li>
1015
</ul>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /