forked from Quazer/anglerfish
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmake_multithread.py
More file actions
56 lines (38 loc) · 1.44 KB
/
make_multithread.py
File metadata and controls
56 lines (38 loc) · 1.44 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Multithreading helper."""
from concurrent.futures import ThreadPoolExecutor
from functools import wraps
__all__ = ("threads", )
class _Threaded():
"""Basic Threaded class."""
__slots__ = ("future", "timeout", "name")
def __init__(self, future, timeout: int):
"""Init _Threaded class, set class attributes."""
self._future, self._timeout = future, timeout
def __getattr__(self, name: str) -> str:
"""Get and return the name attribute."""
result = self._wait()
return result.__getattribute__(name)
def _wait(self):
"""Get wait."""
return self._future.result(self._timeout)
def _async(n, base_type: object, timeout: int=None) -> object:
"""Async internal function for decorator."""
def decorator(f):
"""Decorate builder."""
if isinstance(n, int):
pool = base_type(n)
elif isinstance(n, base_type):
pool = n
else:
raise TypeError(f"Invalid Type: {type(base_type)} for {base_type}")
@wraps(f)
def wrapped(*args, **kwargs):
"""Return the wrapped function."""
return _Threaded(pool.submit(f, *args, **kwargs), timeout=timeout)
return wrapped
return decorator
def threads(n, timeout: int=None) -> object:
"""Convert a simple function to multrithreading."""
return _async(n, ThreadPoolExecutor, timeout)