File: Worker.py

package info (click to toggle)
python-enthoughtbase 3.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 960 kB
  • ctags: 1,034
  • sloc: python: 6,104; makefile: 9; sh: 5
file content (70 lines) | stat: -rw-r--r-- 2,462 bytes parent folder | download | duplicates (2)
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
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
# 
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license.  The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
# Thanks for using Enthought open source!
# 
# Author: Enthought, Inc.
# Description: <Enthought util package component>
#------------------------------------------------------------------------------
import threading

class Worker(threading.Thread):
    """ Performs numerically intensive computations on a separate thread.

    Computations that take more than ~0.1 second should not be run in the 
    same thread as the user interface.

    Typical usage:

    >>> worker = Worker(name = "my worker thread")
    >>> worker.perform_work(my_function_name, args)
    >>> worker.start()
    >>> worker.cancel()
    """

    def __init__(self, **kwds):
        """ Passes the thread constructor a name for the thread.

        Naming threads makes debugging less impossible. The thread is set to be 
        a daemon thread, which means that if is the only remaining executing
        thread the program will terminate. 
        """
        self._stopevent = threading.Event()
        threading.Thread.__init__(self, **kwds)
        self.setDaemon(True)

    def perform_work(self, callable, *args, **kwds):
        """ Indicates to the thread the method or function and it's arguments.

        When the thread begins to run it will execute 'callable' and pass it 
        'args' and 'kwds'
        """
        self.callable = callable
        self.args = args
        self.kwds = kwds

    def run(self):
        """ Private method - used only by the threading.Thread module.

        Users signal a thread should start to run by calling start().
        """
        self.callable(self, *self.args, **self.kwds)

    def cancel(self, timeout = None):
        """ Signals to the worker thread that it should stop computing.

        Calling this method before the thread is started generates an
        exception.
        """
        self._stopevent.set()
        threading.Thread.join(self, timeout)

    def abort(self):
        """ should the algorithm stop computing? 
        """
        return self._stopevent.isSet()