forked from thezakpak/handy_python_scripts
/
process_array_threads_example.py
73 lines (54 loc) · 1.76 KB
/
process_array_threads_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# process_array_threads_example.py
import threading
import multiprocessing
import time
from random import randint
# Create a function to process the items in the array/dictionary
def process_function():
while len(items_to_process) != 0:
item = items_to_process.pop()
print(item)
def use_threads():
start_time = time.time()
items_to_process = []
# Generate an array of random integers from 0-9
for num in range(300):
random_number = randint(0, 9)
items_to_process.append(random_number)
# Create array to hold all of the threads
threads = []
# Create 3 threads to process the data in the array
for i in range(3):
# create thread with target call of the function created above
t = threading.Thread(target=process_function)
# append to array of threads
threads.append(t)
t.start()
# Wait for all of the threads to finish
for thread in threads:
thread.join()
end_time = time.time()
duration_in_seconds = end_time - start_time
print("The script ran in " + str(duration_in_seconds) + " seconds.")
def use_processes():
start_time = time.time()
items_to_process = []
# Generate an array of random integers from 0-9
for num in range(300):
random_number = randint(0, 9)
items_to_process.append(random_number)
# Create array to hold all of the threads
processes = []
# Create 3 threads to process the data in the array
for i in range(3):
# create thread with target call of the function created above
p = multiprocessing.Process(target=process_function)
# append to array of threads
processes.append(p)
p.start()
# Wait for all of the threads to finish
for process in processes:
process.join()
end_time = time.time()
duration_in_seconds = end_time - start_time
print("The script ran in " + str(duration_in_seconds) + " seconds.")