workerpool.py 9.36 KB
Newer Older
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
#
#

# Copyright (C) 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Base classes for worker pools.

"""

import collections
import logging
import threading


class BaseWorker(threading.Thread, object):
  """Base worker class for worker pools.

  Users of a worker pool must override RunTask in a subclass.

  """
Iustin Pop's avatar
Iustin Pop committed
37
  # pylint: disable-msg=W0212
38
39
40
  def __init__(self, pool, worker_id):
    """Constructor for BaseWorker thread.

41
42
    @param pool: the parent worker pool
    @param worker_id: identifier for this worker
43
44

    """
45
    super(BaseWorker, self).__init__(name=worker_id)
46
47
48
49
50
51
52
53
54
    self.pool = pool
    self._current_task = None

  def ShouldTerminate(self):
    """Returns whether a worker should terminate.

    """
    return self.pool.ShouldWorkerTerminate(self)

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  def _HasRunningTaskUnlocked(self):
    """Returns whether this worker is currently running a task.

    """
    return (self._current_task is not None)

  def HasRunningTask(self):
    """Returns whether this worker is currently running a task.

    """
    self.pool._lock.acquire()
    try:
      return self._HasRunningTaskUnlocked()
    finally:
      self.pool._lock.release()

71
72
73
74
75
76
77
78
  def run(self):
    """Main thread function.

    Waits for new tasks to show up in the queue.

    """
    pool = self.pool

79
    assert not self.HasRunningTask()
80
81
82
83
84
85
86
87
88
89
90

    while True:
      try:
        # We wait on lock to be told either terminate or do a task.
        pool._lock.acquire()
        try:
          if pool._ShouldWorkerTerminateUnlocked(self):
            break

          # We only wait if there's no task for us.
          if not pool._tasks:
91
            logging.debug("Waiting for tasks")
92

93
            # wait() releases the lock and sleeps until notified
94
            pool._pool_to_worker.wait()
95

96
            logging.debug("Notified while waiting")
97

98
99
100
101
102
103
104
105
106
107
108
109
            # Were we woken up in order to terminate?
            if pool._ShouldWorkerTerminateUnlocked(self):
              break

            if not pool._tasks:
              # Spurious notification, ignore
              continue

          # Get task from queue and tell pool about it
          try:
            self._current_task = pool._tasks.popleft()
          finally:
110
            pool._worker_to_pool.notifyAll()
111
112
113
114
115
        finally:
          pool._lock.release()

        # Run the actual task
        try:
116
          logging.debug("Starting task %r", self._current_task)
117
          self.RunTask(*self._current_task)
118
          logging.debug("Done with task %r", self._current_task)
Iustin Pop's avatar
Iustin Pop committed
119
        except: # pylint: disable-msg=W0702
120
          logging.exception("Caught unhandled exception")
121
122
123
124
      finally:
        # Notify pool
        pool._lock.acquire()
        try:
125
126
          if self._current_task:
            self._current_task = None
127
            pool._worker_to_pool.notifyAll()
128
129
130
        finally:
          pool._lock.release()

131
    logging.debug("Terminates")
132

133
134
135
  def RunTask(self, *args):
    """Function called to start a task.

136
137
    This needs to be implemented by child classes.

138
139
140
141
142
143
144
145
146
    """
    raise NotImplementedError()


class WorkerPool(object):
  """Worker pool with a queue.

  This class is thread-safe.

147
148
149
  Tasks are guaranteed to be started in the order in which they're
  added to the pool. Due to the nature of threading, they're not
  guaranteed to finish in the same order.
150
151

  """
152
  def __init__(self, name, num_workers, worker_class):
153
154
    """Constructor for worker pool.

155
156
157
158
    @param num_workers: number of workers to be started
        (dynamic resizing is not yet implemented)
    @param worker_class: the class to be instantiated for workers;
        should derive from L{BaseWorker}
159
160
161

    """
    # Some of these variables are accessed by BaseWorker
162
163
164
165
    self._lock = threading.Lock()
    self._pool_to_pool = threading.Condition(self._lock)
    self._pool_to_worker = threading.Condition(self._lock)
    self._worker_to_pool = threading.Condition(self._lock)
166
    self._worker_class = worker_class
167
    self._name = name
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    self._last_worker_id = 0
    self._workers = []
    self._quiescing = False

    # Terminating workers
    self._termworkers = []

    # Queued tasks
    self._tasks = collections.deque()

    # Start workers
    self.Resize(num_workers)

  # TODO: Implement dynamic resizing?

Guido Trotter's avatar
Guido Trotter committed
183
184
185
186
187
188
189
  def _WaitWhileQuiescingUnlocked(self):
    """Wait until the worker pool has finished quiescing.

    """
    while self._quiescing:
      self._pool_to_pool.wait()

190
191
192
  def AddTask(self, *args):
    """Adds a task to the queue.

193
    @param args: arguments passed to L{BaseWorker.RunTask}
194
195
196
197

    """
    self._lock.acquire()
    try:
Guido Trotter's avatar
Guido Trotter committed
198
      self._WaitWhileQuiescingUnlocked()
199
200

      self._tasks.append(args)
201
202
203

      # Wake one idling worker up
      self._pool_to_worker.notify()
204
205
206
    finally:
      self._lock.release()

Guido Trotter's avatar
Guido Trotter committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
  def AddManyTasks(self, tasks):
    """Add a list of tasks to the queue.

    @type tasks: list of tuples
    @param tasks: list of args passed to L{BaseWorker.RunTask}

    """
    self._lock.acquire()
    try:
      self._WaitWhileQuiescingUnlocked()

      self._tasks.extend(tasks)

      for _ in tasks:
        self._pool_to_worker.notify()
    finally:
      self._lock.release()

225
226
227
228
229
230
231
232
233
234
235
236
  def _ShouldWorkerTerminateUnlocked(self, worker):
    """Returns whether a worker should terminate.

    """
    return (worker in self._termworkers)

  def ShouldWorkerTerminate(self, worker):
    """Returns whether a worker should terminate.

    """
    self._lock.acquire()
    try:
237
      return self._ShouldWorkerTerminateUnlocked(worker)
238
239
240
241
242
243
244
245
    finally:
      self._lock.release()

  def _HasRunningTasksUnlocked(self):
    """Checks whether there's a task running in a worker.

    """
    for worker in self._workers + self._termworkers:
Iustin Pop's avatar
Iustin Pop committed
246
      if worker._HasRunningTaskUnlocked(): # pylint: disable-msg=W0212
247
248
249
250
251
252
253
254
255
256
257
258
259
        return True
    return False

  def Quiesce(self):
    """Waits until the task queue is empty.

    """
    self._lock.acquire()
    try:
      self._quiescing = True

      # Wait while there are tasks pending or running
      while self._tasks or self._HasRunningTasksUnlocked():
260
        self._worker_to_pool.wait()
261
262
263
264
265

    finally:
      self._quiescing = False

      # Make sure AddTasks continues in case it was waiting
266
      self._pool_to_pool.notifyAll()
267
268
269
270

      self._lock.release()

  def _NewWorkerIdUnlocked(self):
271
272
273
    """Return an identifier for a new worker.

    """
274
    self._last_worker_id += 1
275
276

    return "%s%d" % (self._name, self._last_worker_id)
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

  def _ResizeUnlocked(self, num_workers):
    """Changes the number of workers.

    """
    assert num_workers >= 0, "num_workers must be >= 0"

    logging.debug("Resizing to %s workers", num_workers)

    current_count = len(self._workers)

    if current_count == num_workers:
      # Nothing to do
      pass

    elif current_count > num_workers:
      if num_workers == 0:
        # Create copy of list to iterate over while lock isn't held.
        termworkers = self._workers[:]
        del self._workers[:]
      else:
        # TODO: Implement partial downsizing
        raise NotImplementedError()
        #termworkers = ...

      self._termworkers += termworkers

      # Notify workers that something has changed
305
      self._pool_to_worker.notifyAll()
306
307
308
309
310

      # Join all terminating workers
      self._lock.release()
      try:
        for worker in termworkers:
311
          logging.debug("Waiting for thread %s", worker.getName())
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
          worker.join()
      finally:
        self._lock.acquire()

      # Remove terminated threads. This could be done in a more efficient way
      # (del self._termworkers[:]), but checking worker.isAlive() makes sure we
      # don't leave zombie threads around.
      for worker in termworkers:
        assert worker in self._termworkers, ("Worker not in list of"
                                             " terminating workers")
        if not worker.isAlive():
          self._termworkers.remove(worker)

      assert not self._termworkers, "Zombie worker detected"

    elif current_count < num_workers:
      # Create (num_workers - current_count) new workers
329
      for _ in range(num_workers - current_count):
330
331
332
333
334
335
336
        worker = self._worker_class(self, self._NewWorkerIdUnlocked())
        self._workers.append(worker)
        worker.start()

  def Resize(self, num_workers):
    """Changes the number of workers in the pool.

337
    @param num_workers: the new number of workers
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363

    """
    self._lock.acquire()
    try:
      return self._ResizeUnlocked(num_workers)
    finally:
      self._lock.release()

  def TerminateWorkers(self):
    """Terminate all worker threads.

    Unstarted tasks will be ignored.

    """
    logging.debug("Terminating all workers")

    self._lock.acquire()
    try:
      self._ResizeUnlocked(0)

      if self._tasks:
        logging.debug("There are %s tasks left", len(self._tasks))
    finally:
      self._lock.release()

    logging.debug("All workers terminated")