File: Thread.py

package info (click to toggle)
atheist 0.20110402-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,348 kB
  • sloc: python: 4,764; xml: 626; makefile: 113; cpp: 54; ansic: 5; sh: 5
file content (434 lines) | stat: -rw-r--r-- 11,450 bytes parent folder | download | duplicates (3)
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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# -*- mode: python; coding: utf-8 -*-

"""threads module provides useful structures for concurrent and
threading programming tools.

.. moduleauthor:: Arco Research Group

"""
from __future__ import with_statement

import threading
import logging
import time
import Queue


class ThreadFunc(threading.Thread):
    """If it is needed to execute the function on another thread and stop is
    requiered. Otherwise, use thread.start_new_thread
    """

    def __init__(self, function, args=(), kargs={}, start=True):
        threading.Thread.__init__(self, name=function.__name__)
        self.function = function
        self.args = args
        self.kargs = kargs
        self.active = threading.Event()
        self.active.set()
        if start:
            self.start()

    def cancel(self):
        self.active.clear()

    def run(self):
        self.function(*self.args, **self.kargs)


class ThreadTimeout(threading.Thread):
    """ Run a function each interval seconds. Function must return
    'True' to continue executing. Based on threding.Timer class """

    def __init__(self, interval, function, args=[], at_init=False):
        threading.Thread.__init__(self, name=function.__name__)
        self.interval = interval # secs
        self.function = function
        self.args = args
        self.at_init = at_init
        self.finished = threading.Event()
        self.play = threading.Event()
        self.start()

    def __del__(self):
        self.cancel()

    def cancel(self):
        "terminates the thread"
        self.play.set()
        self.finished.set()

    def pause(self):
        self.play.clear()

    def play(self):
        self.play.set()

    def run(self):
        if self.at_init:
            if not self.function(*self.args): return

        while 1:
            self.finished.wait(self.interval)
            if self.finished.isSet(): break
            if not self.function(*self.args): break


class EventPool(threading.Thread):
    '''Event pool based exclusively upon threads.'''

    class Task:
        def __init__(self, ctx, interval, func, args=[]):
            self.ctx = ctx
            self.interval = interval
            self.function = func
            self.args = args
            self.diff = interval


        def __repr__(self):
            return "%s.%s i:%s, d:%s" % (self.ctx.name, self.function.__name__,
                                          self.interval, self.diff)


    class Context:
        def __init__(self, poll, persistent, name=''):
            self.pool = poll
            self.persistent = persistent
            self.name = name
            self.tasks = []
            self.reset = self.add


        def add_func(self, interval, func, *args):
            retval = EventPool.Task(self, interval, func, args)
            self.add(retval)
            return retval


        def new_task(self, interval, function, *args):
            return EventPool.Task(self, interval, function, args)


        def add(self, task):
            if task not in self.tasks: self.tasks.append(task)
            self.pool.add_task(task)
            return task


        def cancel(self, task=None):
            if isinstance(task, EventPool.Task):
                try:
                    self.tasks.remove(task)
                except ValueError:
                    return

                self.pool.cancel_task_now(task)
                return

            if task == None:
                task = self.tasks[:]

            if isinstance(task, list):
                for t in task:
                    self.cancel(t)


        def __repr__(self):
            return repr(self.tasks)


    def __init__(self, persistent=True, name=None):
        threading.Thread.__init__(self, name=name)
        self.persistent = persistent
        self.name = name
        self.lock = threading.RLock()
        self.finished = threading.Event()
        self.__contexts = []
        self.__tasks = []
        self.__added = []


    def new_context(self, persistent=True, name=''):
        # deny if thread is running
        ctx = EventPool.Context(self, persistent, name)
        self.__contexts.append(ctx)
        return ctx


    def add_task(self, task):
        self.__added.append(task)


    def cancel_task_now(self, task):
        self.lock.acquire()

        if task in self.__added:
            self.__added.remove(task)
        else:
            self.__cancel_task(task)
        self.lock.release()


    def close(self):
        self.finished.set()


    def __add_task(self, new_task):
        total = 0
        for i,t in enumerate(self.__tasks):
            if total + t.diff > new_task.interval:
                new_task.diff = new_task.interval - total
                t.diff -= new_task.diff
                self.__tasks.insert(i,  new_task)
                return

            total += t.diff

        new_task.diff = new_task.interval - total
        self.__tasks.append(new_task)


    def __cancel_task(self, task):
        if task not in self.__tasks:
            return

        i = self.__tasks.index(task)
        if len(self.__tasks) > i+1:
            self.__tasks[i+1].diff += task.diff

        self.__tasks.remove(task)


    def __pending(self):
        for t in self.__added:
             if t in self.__tasks:
                 self.__cancel_task(t)
             self.__add_task(t)


        self.__added = []

        # clear empty __contexts
        for c in self.__contexts:
            if not c.persistent and not c.tasks:
                self.__contexts.remove(c)

        if not self.persistent and not self.__contexts:
            self.finished.set()


    def run(self):
        while not self.finished.isSet():
            self.lock.acquire()
            self.__pending()

            while self.__tasks and self.__tasks[0].diff <= 0:
                task = self.__tasks[0]
                self.__tasks.remove(task)

                result = task.function(*task.args)

                if result:
                    self.__add_task(task)
                else:
                    try:
                        task.ctx.tasks.remove(task)
                    except ValueError:
                        pass

            if self.__tasks:
                self.__tasks[0].diff -= 1

            self.lock.release()
            time.sleep(1)



# from http://code.activestate.com/recipes/203871/
class ThreadPool:

    class JoiningEx: pass

    """ Flexible thread pool class.  Creates a pool of threads, then
    accepts tasks that will be dispatched to the next available
    thread """

    def __init__(self, numThreads):
        """Initialize the thread pool with numThreads workers """

        self.__threads = []
        self.__resizeLock = threading.Lock()
        self.__taskLock = threading.Condition(threading.Lock())
        self.__tasks = []
        self.__isJoining = False
        self.resize(numThreads)


    def resize(self, newsize):
        """ public method to set the current pool size """

        if self.__isJoining:
            raise ThreadPool.JoiningEx()

        with self.__resizeLock:
            self.__resize(newsize)

        return True


    def __resize(self, newsize):
        """Set the current pool size, spawning or terminating threads
        if necessary.  Internal use only; assumes the resizing lock is
        held."""

        diff = newsize - len(self.__threads)

        # If we need to grow the pool, do so
        for i in range(diff):
            self.__threads.append(ThreadPool.Worker(self))

        # If we need to shrink the pool, do so
        for i in range(-diff):
            thread = self.__threads.pop()
            thread.stop = True


    def __len__(self):
        """Return the number of threads in the pool."""

        with self.__resizeLock:
            return len(self.__threads)


    def add(self, task, args=None, callback=None):
        """Insert a task into the queue.  task must be callable;
        args and taskCallback can be None."""

        assert callable(task)

        if self.__isJoining:
            raise ThreadPool.JoiningEx()

        with self.__taskLock:
            self.__tasks.append((task, args, callback))
            self.__taskLock.notify()
            return True



    def nextTask(self):
        """ Retrieve the next task from the task queue.  For use
        only by ThreadPoolWorker objects contained in the pool """

        with self.__taskLock:
            while not self.__tasks:
                if self.__isJoining:
                    raise ThreadPool.JoiningEx()

                self.__taskLock.wait()

            assert self.__tasks
            return self.__tasks.pop(0)



    def join(self, waitForTasks=True, waitForThreads=True):
        """ Clear the task queue and terminate all pooled threads,
        optionally allowing the tasks and threads to finish """

        self.__isJoining = True  # prevent more task queueing

        if waitForTasks:
            while self.__tasks:
                time.sleep(0.1)

        with self.__resizeLock:
            if waitForThreads:
                with self.__taskLock:
                    self.__taskLock.notifyAll()

                for t in self.__threads:
                    t.join()

            # ready to reuse
            del self.__threads[:]
            self.__isJoining = False



    class Worker(threading.Thread):
        """ Pooled thread class """

        def __init__(self, pool):
            """ Initialize the thread and remember the pool. """

            threading.Thread.__init__(self)
            self.__pool = pool
            self.stop = False
            self.start()


        def run(self):
            """ Until told to quit, retrieve the next task and execute
            it, calling the callback if any.  """

            while not self.stop:
                try:
                    cmd, args, callback = self.__pool.nextTask()
                except ThreadPool.JoiningEx:
                    break

                logging.debug("thread %s taken %s" % (self, cmd))

                result = cmd(*args)
                if callback:
                    callback(result)


class SimpleThreadPool:
    def __init__(self, numThreads):
        self.tasks = Queue.Queue()
        self.threads = [SimpleThreadPool.Worker(self.tasks) for x  in range(numThreads)]

    def add(self, func, args=None, callback=None):
        assert callable(func)
        self.tasks.put((func, args, callback))

    def map(self, func, values):
        holders = [SimpleThreadPool.Holder() for x in range(len(values))]

        for value, callback in zip(values, holders):
            self.add(func, (value,), callback)
        self.join()

        return [x.value for x in holders]

    def join(self):
        self.tasks.join()


    class Worker(threading.Thread):
        def __init__(self, tasks):
            threading.Thread.__init__(self)
            self.tasks = tasks
            self.daemon = True
            self.start()

        def run(self):
            while 1:
                func, args, callback = self.tasks.get()

                logging.debug("thread %s taken %s", self, func)
                result = func(*args)
                self.tasks.task_done()

                if callback:
                    callback(result)

    class Holder:
        def __init__(self):
            self.value = None

        def __call__(self, arg):
            self.value = arg