| OLD | NEW |
| 1 # Copyright 2017 The Chromium Authors. All rights reserved. | 1 # Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
| 4 | 4 |
| 5 """Utility methods.""" | 5 """Utility methods.""" |
| 6 | 6 |
| 7 import atexit |
| 8 import multiprocessing |
| 7 import os | 9 import os |
| 10 import threading |
| 8 | 11 |
| 9 | 12 |
| 10 SRC_ROOT = os.path.dirname( | 13 SRC_ROOT = os.path.dirname( |
| 11 os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) | 14 os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) |
| 15 |
| 16 |
| 17 def MakeProcessPool(*args): |
| 18 """Wrapper for multiprocessing.Pool, with fix to terminate on exit.""" |
| 19 ret = multiprocessing.Pool(*args) |
| 20 def close_pool(): |
| 21 ret.terminate() |
| 22 |
| 23 def on_exit(): |
| 24 thread = threading.Thread(target=close_pool) |
| 25 thread.daemon = True |
| 26 thread.start() |
| 27 |
| 28 # Without calling terminate() on a separate thread, the call can block |
| 29 # forever. |
| 30 atexit.register(on_exit) |
| 31 return ret |
| 32 |
| 33 |
| 34 def ForkAndCall(func, *args, **kwargs): |
| 35 """Uses multiprocessing to run the given function in a fork'ed process. |
| 36 |
| 37 Returns: |
| 38 A Result object (call .get() to get the return value) |
| 39 """ |
| 40 pool_of_one = MakeProcessPool(1) |
| 41 result = pool_of_one.apply_async(func, args=args, kwds=kwargs) |
| 42 pool_of_one.close() |
| 43 return result |
| OLD | NEW |