|
1 | 1 | import re |
| 2 | +from concurrent.futures.thread import ThreadPoolExecutor |
| 3 | +from functools import partial |
| 4 | +from typing import Callable, Sequence, Tuple, List |
2 | 5 |
|
3 | 6 | from .constants import SHA_COINS, SCRYPT_COINS, ETHASH_COINS, COIN_SYMBOL_SET, COIN_SYMBOL_MAPPINGS, FIRST4_MKEY_CS_MAPPINGS_UPPER, UNIT_CHOICES, UNIT_MAPPINGS |
4 | 7 | from .crypto import script_to_address |
@@ -521,3 +524,47 @@ def is_valid_address_for_coinsymbol(b58_address, coin_symbol): |
521 | 524 | if is_valid_address(b58_address): |
522 | 525 | return True |
523 | 526 | return False |
| 527 | + |
| 528 | + |
| 529 | +def delegate_task(task: Callable, workers: int = 2, use_max: bool = False, args: List | Tuple = None, **kwargs): |
| 530 | + """ |
| 531 | + Execute a wrapped function on separate thread using ThreadPoolExecutor. |
| 532 | + The result of executing the wrapped function is passed to another system or caller. |
| 533 | + This function should be used for accessing blockchain operations that are IO bound |
| 534 | +
|
| 535 | + :param task: a function or any callable that will be executed on a separate thread |
| 536 | + :type task: callable |
| 537 | + :param workers: the number of threads in the thread pool for executing the wrapped function |
| 538 | + :type workers: int |
| 539 | + :param use_max: boolean flag to indicate if the maximum system thread pool should be used. |
| 540 | + :type use_max: bool |
| 541 | + :param args: list or tuple of argument to be passed to the task or function being executed |
| 542 | + :type args: list | tuple |
| 543 | + :param kwargs: mapping of keyword arguments to be passed to the task or function to be executed |
| 544 | + :type kwargs: dict |
| 545 | + :return: Returns the result of executing the callable or function |
| 546 | + :rtype: Any |
| 547 | +
|
| 548 | + Example |
| 549 | + ======= |
| 550 | + >>> from blockcypher import get_transaction_details |
| 551 | + >>> tranx = 'f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449' |
| 552 | + >>> result = delegate_task(get_transaction_details, workers=2, use_max=False, args=[tranx]) |
| 553 | + >>> print(result) |
| 554 | + """ |
| 555 | + if workers < 0: |
| 556 | + workers = 2 |
| 557 | + if workers > 5: |
| 558 | + workers = 5 |
| 559 | + if use_max: |
| 560 | + workers = 5 |
| 561 | + with ThreadPoolExecutor(max_workers=workers) as ex: |
| 562 | + if args and kwargs: |
| 563 | + future = ex.submit(task, *args, **kwargs) |
| 564 | + elif args and not kwargs: |
| 565 | + future = ex.submit(task, *args) |
| 566 | + elif kwargs and not args: |
| 567 | + future = ex.submit(task, **kwargs) |
| 568 | + else: |
| 569 | + future = ex.submit(task) |
| 570 | + return future.result() |
0 commit comments