-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathparallel.py
More file actions
69 lines (58 loc) · 1.75 KB
/
parallel.py
File metadata and controls
69 lines (58 loc) · 1.75 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from __future__ import print_function
import time
try:
import queue
except ImportError:
import Queue as queue
import threading
from multiprocessing.pool import ThreadPool
stopSign = False
def run(task, values, thread_num=8, verb=False, max_retries=5):
global stopSign
threads = []
stopSign = False
valueQueue = queue.Queue()
for v in values:
valueQueue.put(v)
def __inner_func():
while not stopSign:
_retry = max_retries
try:
arguments = valueQueue.get_nowait()
except:
break
while _retry >= 0:
try:
task(arguments)
_retry = -1
except Exception as e:
verb and print(e)
verb and print("retrying... %d" % arguments)
_retry -= 1
time.sleep(0.3)
valueQueue.task_done()
for i in range(thread_num):
t = threading.Thread(target=__inner_func)
t.daemon = True
t.start()
threads.append(t)
while not valueQueue.empty() and not stopSign:
try:
time.sleep(0.6)
except KeyboardInterrupt:
verb and print('ready to stop...')
break
stopSign = True
verb and print('task done! remaining queue size: %d' % valueQueue.qsize())
for t in threads:
t.join()
if __name__ == '__main__':
import requests
try:
print("launch test http server first")
print("$ python3 -m http.server 3333")
input("press [enter] to continue...")
except SyntaxError:
pass
fn = lambda x: requests.get("http://localhost:3333/" + str(x))
run(fn, range(1000), verb=True)