Skip to content

tracking_executor

A task-tracking executor wrapper.

This module provides TrackingExecutor, an executor wrapper which keeps track of the tasks being executed, allowing to wait for the completion of specific tasks - or of all the submitted tasks - with completion notification delivered via condition variables.

TrackingExecutor

An executor wrapper tracking the lifecycle of the submitted tasks.

Each submitted task gets a unique id, and the executor keeps track of the tasks still pending - i.e. not yet completed - so that the callers can wait for their completion.

A TrackingExecutor is not the owner of its underlying executor: it does not close it when being closed itself.

Example
import time
import py_misc_utils.executor as xe
import py_misc_utils.tracking_executor as te

tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
tid = tex.submit(time.sleep, 0.01)
tex.submit(time.sleep, 0.01)
assert tex.wait(timeout=2.0)      # all tracked tasks completed
assert tex.wait_for_idle(timeout=2.0)  # and workers are idle too
tex.shutdown()
Source code in py_misc_utils/tracking_executor.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
class TrackingExecutor:
  """An executor wrapper tracking the lifecycle of the submitted tasks.

  Each submitted task gets a unique id, and the executor keeps track of
  the tasks still pending - i.e. not yet completed - so that the callers
  can wait for their completion.

  A TrackingExecutor is not the owner of its underlying executor: it does
  not close it when being closed itself.

  Example:
    import time
    import py_misc_utils.executor as xe
    import py_misc_utils.tracking_executor as te

    tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
    tid = tex.submit(time.sleep, 0.01)
    tex.submit(time.sleep, 0.01)
    assert tex.wait(timeout=2.0)      # all tracked tasks completed
    assert tex.wait_for_idle(timeout=2.0)  # and workers are idle too
    tex.shutdown()
  """

  def __init__(self, executor=None):
    """Creates a tracking executor.

    Args:
      executor: An optional executor to which the tasks are submitted. If
        None, the common (shared) executor is used.
    """
    self.executor = executor if executor is not None else xe.common_executor()
    self._lock = threading.Lock()
    self._task_id = 0
    self._pending = set()
    self._pending_cv = threading.Condition(lock=self._lock)

  def _report_done(self, tid):
    """Marks a task as completed, notifying the waiters."""
    with self._lock:
      self._pending.remove(tid)
      self._pending_cv.notify_all()

  def _wrap(self, fn, *args, **kwargs):
    """Wraps a task function and registers it as pending.

    Args:
      fn: The function to execute.
      *args: Positional arguments to pass to the function.
      **kwargs: Keyword arguments to pass to the function.

    Returns:
      A (wrapped task function, task id) tuple.
    """
    with self._lock:
      wfn = _wrap_task(self, self._task_id, fn, *args, **kwargs)
      self._pending.add(self._task_id)
      self._task_id += 1

      return wfn, self._task_id - 1

  def submit(self, fn, *args, **kwargs):
    """Submits a task for execution.

    Args:
      fn: The function to execute.
      *args: Positional arguments to pass to the function.
      **kwargs: Keyword arguments to pass to the function.

    Returns:
      The unique task id assigned to the submitted task.

    Raises:
      Exception: If the underlying executor fails to accept the task - in
        which case the task is not tracked as pending anymore.
    """
    wfn, tid = self._wrap(fn, *args, **kwargs)
    try:
      self.executor.submit(wfn)
    except Exception:
      self._report_done(tid)
      raise

    return tid

  def submit_result(self, fn, *args, **kwargs):
    """Submits a task for execution, returning a result-holder object.

    The returned holder also tracks the task, so wait()/wait_for_idle()
    accounts for it - and wait() on the holder re-raises any task failure.

    Args:
      fn: The function to execute.
      *args: Positional arguments to pass to the function.
      **kwargs: Keyword arguments to pass to the function.

    Returns:
      A result-holder object - allowing to retrieve the task result and to
      wait for its completion - as returned by the underlying executor.

    Raises:
      Exception: If the underlying executor fails to accept the task - in
        which case the task is not tracked as pending anymore.
    """
    wfn, tid = self._wrap(fn, *args, **kwargs)
    try:
      return self.executor.submit_result(wfn)
    except Exception:
      self._report_done(tid)
      raise

  def shutdown(self):
    """Shuts down the underlying executor, waiting for all the pending
    tasks to complete.

    Example:
      import py_misc_utils.executor as xe
      import py_misc_utils.tracking_executor as te

      tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
      holder = tex.submit_result(len, 'abcd')
      assert holder.wait() == 4
      tex.shutdown()
    """
    self.executor.shutdown()
    self.wait()

  def wait(self, tids=None, timeout=None, timegen=None, waiter=None):
    """Waits for the completion of one or more tasks.

    Args:
      tids: An optional list of task ids to wait for. If None, all the
        tasks still pending are waited for.
      timeout: An optional maximum number of seconds to wait.
      timegen: An optional TimeGen object used to evaluate the timeout.
      waiter: An optional pre-built waiter object to be used - instead of
        building one from the timeout and timegen arguments.

    Returns:
      True if all the waited-for tasks are completed, False if the wait
      ended by timeout expiry.

    Example:
      import time
      import py_misc_utils.executor as xe
      import py_misc_utils.tracking_executor as te

      tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
      tid = tex.submit(time.sleep, 0.01)
      assert tex.wait(tids=[tid], timeout=2.0)
      tex.shutdown()
    """
    waiter = waiter or cwait.CondWaiter(timeout=timeout, timegen=timegen)
    if not tids:
      with self._lock:
        while self._pending:
          if not waiter.wait(self._pending_cv):
            break

        return not self._pending
    else:
      stids = set(tids)
      with self._lock:
        while True:
          rem = stids & self._pending
          if not (rem and waiter.wait(self._pending_cv)):
            break

        return not rem

  def wait_for_idle(self, timeout=None, timegen=None):
    """Waits for both the tracked tasks - and the underlying executor -
    to be idle.

    Args:
      timeout: An optional maximum number of seconds to wait.
      timegen: An optional TimeGen object used to evaluate the timeout.

    Returns:
      True if the executor is idle, False if the wait ended by timeout
      expiry.
    """
    waiter = cwait.CondWaiter(timeout=timeout, timegen=timegen)

    return self.wait(waiter=waiter) and self.executor.wait_for_idle(waiter=waiter)

submit(fn, *args, **kwargs)

Submits a task for execution.

Parameters:

Name Type Description Default
fn

The function to execute.

required
*args

Positional arguments to pass to the function.

()
**kwargs

Keyword arguments to pass to the function.

{}

Returns:

Type Description

The unique task id assigned to the submitted task.

Raises:

Type Description
Exception

If the underlying executor fails to accept the task - in which case the task is not tracked as pending anymore.

Source code in py_misc_utils/tracking_executor.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def submit(self, fn, *args, **kwargs):
  """Submits a task for execution.

  Args:
    fn: The function to execute.
    *args: Positional arguments to pass to the function.
    **kwargs: Keyword arguments to pass to the function.

  Returns:
    The unique task id assigned to the submitted task.

  Raises:
    Exception: If the underlying executor fails to accept the task - in
      which case the task is not tracked as pending anymore.
  """
  wfn, tid = self._wrap(fn, *args, **kwargs)
  try:
    self.executor.submit(wfn)
  except Exception:
    self._report_done(tid)
    raise

  return tid

submit_result(fn, *args, **kwargs)

Submits a task for execution, returning a result-holder object.

The returned holder also tracks the task, so wait()/wait_for_idle() accounts for it - and wait() on the holder re-raises any task failure.

Parameters:

Name Type Description Default
fn

The function to execute.

required
*args

Positional arguments to pass to the function.

()
**kwargs

Keyword arguments to pass to the function.

{}

Returns:

Type Description

A result-holder object - allowing to retrieve the task result and to

wait for its completion - as returned by the underlying executor.

Raises:

Type Description
Exception

If the underlying executor fails to accept the task - in which case the task is not tracked as pending anymore.

Source code in py_misc_utils/tracking_executor.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def submit_result(self, fn, *args, **kwargs):
  """Submits a task for execution, returning a result-holder object.

  The returned holder also tracks the task, so wait()/wait_for_idle()
  accounts for it - and wait() on the holder re-raises any task failure.

  Args:
    fn: The function to execute.
    *args: Positional arguments to pass to the function.
    **kwargs: Keyword arguments to pass to the function.

  Returns:
    A result-holder object - allowing to retrieve the task result and to
    wait for its completion - as returned by the underlying executor.

  Raises:
    Exception: If the underlying executor fails to accept the task - in
      which case the task is not tracked as pending anymore.
  """
  wfn, tid = self._wrap(fn, *args, **kwargs)
  try:
    return self.executor.submit_result(wfn)
  except Exception:
    self._report_done(tid)
    raise

shutdown()

Shuts down the underlying executor, waiting for all the pending tasks to complete.

Example
import py_misc_utils.executor as xe
import py_misc_utils.tracking_executor as te

tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
holder = tex.submit_result(len, 'abcd')
assert holder.wait() == 4
tex.shutdown()
Source code in py_misc_utils/tracking_executor.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def shutdown(self):
  """Shuts down the underlying executor, waiting for all the pending
  tasks to complete.

  Example:
    import py_misc_utils.executor as xe
    import py_misc_utils.tracking_executor as te

    tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
    holder = tex.submit_result(len, 'abcd')
    assert holder.wait() == 4
    tex.shutdown()
  """
  self.executor.shutdown()
  self.wait()

wait(tids=None, timeout=None, timegen=None, waiter=None)

Waits for the completion of one or more tasks.

Parameters:

Name Type Description Default
tids

An optional list of task ids to wait for. If None, all the tasks still pending are waited for.

None
timeout

An optional maximum number of seconds to wait.

None
timegen

An optional TimeGen object used to evaluate the timeout.

None
waiter

An optional pre-built waiter object to be used - instead of building one from the timeout and timegen arguments.

None

Returns:

Type Description

True if all the waited-for tasks are completed, False if the wait

ended by timeout expiry.

Example
import time
import py_misc_utils.executor as xe
import py_misc_utils.tracking_executor as te

tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
tid = tex.submit(time.sleep, 0.01)
assert tex.wait(tids=[tid], timeout=2.0)
tex.shutdown()
Source code in py_misc_utils/tracking_executor.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def wait(self, tids=None, timeout=None, timegen=None, waiter=None):
  """Waits for the completion of one or more tasks.

  Args:
    tids: An optional list of task ids to wait for. If None, all the
      tasks still pending are waited for.
    timeout: An optional maximum number of seconds to wait.
    timegen: An optional TimeGen object used to evaluate the timeout.
    waiter: An optional pre-built waiter object to be used - instead of
      building one from the timeout and timegen arguments.

  Returns:
    True if all the waited-for tasks are completed, False if the wait
    ended by timeout expiry.

  Example:
    import time
    import py_misc_utils.executor as xe
    import py_misc_utils.tracking_executor as te

    tex = te.TrackingExecutor(xe.Executor(max_threads=2, min_threads=1))
    tid = tex.submit(time.sleep, 0.01)
    assert tex.wait(tids=[tid], timeout=2.0)
    tex.shutdown()
  """
  waiter = waiter or cwait.CondWaiter(timeout=timeout, timegen=timegen)
  if not tids:
    with self._lock:
      while self._pending:
        if not waiter.wait(self._pending_cv):
          break

      return not self._pending
  else:
    stids = set(tids)
    with self._lock:
      while True:
        rem = stids & self._pending
        if not (rem and waiter.wait(self._pending_cv)):
          break

      return not rem

wait_for_idle(timeout=None, timegen=None)

Waits for both the tracked tasks - and the underlying executor - to be idle.

Parameters:

Name Type Description Default
timeout

An optional maximum number of seconds to wait.

None
timegen

An optional TimeGen object used to evaluate the timeout.

None

Returns:

Type Description

True if the executor is idle, False if the wait ended by timeout

expiry.

Source code in py_misc_utils/tracking_executor.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def wait_for_idle(self, timeout=None, timegen=None):
  """Waits for both the tracked tasks - and the underlying executor -
  to be idle.

  Args:
    timeout: An optional maximum number of seconds to wait.
    timegen: An optional TimeGen object used to evaluate the timeout.

  Returns:
    True if the executor is idle, False if the wait ended by timeout
    expiry.
  """
  waiter = cwait.CondWaiter(timeout=timeout, timegen=timegen)

  return self.wait(waiter=waiter) and self.executor.wait_for_idle(waiter=waiter)