forked from tritemio/transfer_convert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_example.py
More file actions
51 lines (40 loc) · 1.38 KB
/
pool_example.py
File metadata and controls
51 lines (40 loc) · 1.38 KB
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
"""
Test/mockup for the multiprocessing scheme.
"""
from multiprocessing import Pool
from functools import partial
import time
import sys
import random
def get_new_files():
print('getting new files ...', flush=True)
num_files = random.randint(0, 1)
wait = random.randint(1, 3)
time.sleep(wait)
fname = [] if num_files == 0 else [random.randint(1, 10000)]
print(fname, flush=True)
return fname
def process(newfile):
sys.stdout = open("%s.txt" % newfile, "w")
print(' - Processing %d ...' % newfile, flush=True)
wait = random.randint(1, 3)
time.sleep(wait)
print(' * DONE %d' % newfile, flush=True)
return newfile
def copy_log(res, dry_run=False):
print('callback for file %d () dry_run=%s' % (res, dry_run), flush=True)
with open('%s.txt' % res) as f:
print(f.readlines(), flush=True)
if __name__ == '__main__':
dry_run = True
copy_log = partial(copy_log, dry_run=dry_run)
# start 4 worker processes
with Pool(processes=4) as pool:
for i in range(5):
time.sleep(1)
newfiles = get_new_files()
for newfile in newfiles:
pool.apply_async(process, (newfile,), callback=copy_log)
print("For the moment, the pool remains available for more work")
# exiting the 'with'-block has stopped the pool
print("Now the pool is closed and no longer available")