threading.py 1.2 KB

123456789101112131415161718192021222324252627282930
  1. import os
  2. from concurrent.futures import Future, ThreadPoolExecutor
  3. from hivemind.utils import get_logger
  4. logger = get_logger(__name__)
  5. EXECUTOR_PID, GLOBAL_EXECUTOR = None, None
  6. def run_in_background(func: callable, *args, **kwargs) -> Future:
  7. """ run func(*args, **kwargs) in background and return Future for its outputs """
  8. global EXECUTOR_PID, GLOBAL_EXECUTOR
  9. if os.getpid() != EXECUTOR_PID:
  10. GLOBAL_EXECUTOR = ThreadPoolExecutor(max_workers=os.environ.get("HIVEMIND_THREADS", float('inf')))
  11. EXECUTOR_PID = os.getpid()
  12. return GLOBAL_EXECUTOR.submit(func, *args, **kwargs)
  13. def increase_file_limit(new_soft=2 ** 15, new_hard=2 ** 15):
  14. """ Increase the maximum number of open files. On Linux, this allows spawning more processes/threads. """
  15. try:
  16. import resource # local import to avoid ImportError for Windows users
  17. soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
  18. new_soft = max(soft, new_soft)
  19. new_hard = max(hard, new_hard)
  20. logger.info(f"Increasing file limit: soft {soft}=>{new_soft}, hard {hard}=>{new_hard}")
  21. return resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft, new_hard))
  22. except Exception as e:
  23. logger.warning(f"Failed to increase file limit: {e}")