File tree Expand file tree Collapse file tree 3 files changed +69
-0
lines changed Expand file tree Collapse file tree 3 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ from concurrent .futures import ThreadPoolExecutor , ProcessPoolExecutor
2
+ from multiprocessing import Value
3
+
4
+ # define a function to increment the value by 1
5
+ def inc (i ):
6
+ val .value += 1
7
+
8
+ # using a large number to see the problem
9
+ n = 100000
10
+
11
+ # create a shared data and initialize it to 0
12
+ val = Value ('i' , 0 )
13
+ with ThreadPoolExecutor (max_workers = 4 ) as pool :
14
+ pool .map (inc , range (n ))
15
+
16
+ print (val .value )
17
+
18
+ # create a shared data and initialize it to 0
19
+ val = Value ('i' , 0 )
20
+ with ProcessPoolExecutor (max_workers = 4 ) as pool :
21
+ pool .map (inc , range (n ))
22
+
23
+ print (val .value )
Original file line number Diff line number Diff line change
1
+ from concurrent .futures import ProcessPoolExecutor
2
+ from multiprocessing import Array
3
+
4
+
5
+ # define a function to increment the value by 1
6
+ def inc (i ):
7
+ ind = mp .current_process ().ident % 4
8
+ arr [ind ] += 1
9
+
10
+ # define a large number
11
+ n = 100000
12
+
13
+ # create a shared data and initialize it to 0
14
+ arr = Array ('i' , [0 ]* 4 )
15
+ with ProcessPoolExecutor (max_workers = 4 ) as pool :
16
+ pool .map (inc , range (n ))
17
+
18
+ print (arr [:],sum (arr ))
Original file line number Diff line number Diff line change
1
+ from concurrent .futures import ThreadPoolExecutor , ProcessPoolExecutor
2
+ from multiprocessing import Value , Lock
3
+
4
+ lock = Lock ()
5
+
6
+ # adding lock
7
+ def inc (i ):
8
+ lock .acquire ()
9
+ val .value += 1
10
+ lock .release ()
11
+
12
+
13
+ # define a large number
14
+ n = 100000
15
+
16
+ # create a shared data and initialize it to 0
17
+ val = Value ('i' , 0 )
18
+ with ThreadPoolExecutor (max_workers = 4 ) as pool :
19
+ pool .map (inc , range (n ))
20
+
21
+ print (val .value )
22
+
23
+ # create a shared data and initialize it to 0
24
+ val = Value ('i' , 0 )
25
+ with ProcessPoolExecutor (max_workers = 4 ) as pool :
26
+ pool .map (inc , range (n ))
27
+
28
+ print (val .value )
You can’t perform that action at this time.
0 commit comments