forked from SuperFastPython/PythonThreadPoolJumpStart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlesson02_initializer.py
More file actions
28 lines (25 loc) · 780 Bytes
/
Copy pathlesson02_initializer.py
File metadata and controls
28 lines (25 loc) · 780 Bytes
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
# SuperFastPython.com
# example initializing worker threads in the pool
from time import sleep
from multiprocessing.pool import ThreadPool
# custom function to be executed in a worker thread
def task():
# report a message
print('Worker executing task...')
# block for a moment
sleep(1)
# initialize a worker in the thread pool
def init():
# report a message
print('Initializing worker...')
# protect the entry point
if __name__ == '__main__':
# create and configure the thread pool
with ThreadPool(2, initializer=init) as pool:
# issue tasks to the thread pool
for _ in range(4):
pool.apply_async(task)
# close the thread pool
pool.close()
# wait for all tasks to complete
pool.join()