forked from graphql-python/graphql-core-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.py
47 lines (37 loc) · 1.31 KB
/
thread.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
from multiprocessing.pool import ThreadPool
from threading import Thread
from promise import Promise
from .utils import process
# Necessary for static type checking
if False: # flake8: noqa
from typing import Any, Callable, List
class ThreadExecutor(object):
pool = None
def __init__(self, pool=False):
# type: (bool) -> None
self.threads = [] # type: List[Thread]
if pool:
self.execute = self.execute_in_pool
self.pool = ThreadPool(processes=pool)
else:
self.execute = self.execute_in_thread
def wait_until_finished(self):
# type: () -> None
while self.threads:
threads = self.threads
self.threads = []
for thread in threads:
thread.join()
def clean(self):
self.threads = []
def execute_in_thread(self, fn, *args, **kwargs):
# type: (Callable, *Any, **Any) -> Promise
promise = Promise() # type: ignore
thread = Thread(target=process, args=(promise, fn, args, kwargs))
thread.start()
self.threads.append(thread)
return promise
def execute_in_pool(self, fn, *args, **kwargs):
promise = Promise()
self.pool.map(lambda input: process(*input), [(promise, fn, args, kwargs)])
return promise