| 1 |
# (C) Copyright 2004-2023 Enthought, Inc., Austin, TX |
| 2 |
# All rights reserved. |
| 3 |
# |
| 4 |
# This software is provided without warranty under the terms of the BSD |
| 5 |
# license included in LICENSE.txt and may be redistributed only under |
| 6 |
# the conditions described in the aforementioned license. The license |
| 7 |
# is also available online at http://www.enthought.com/licenses/BSD.txt |
| 8 |
# |
| 9 |
# Thanks for using Enthought open source! |
| 10 |
|
| 11 |
""" |
| 12 |
Monitoring threads in the user interface |
| 13 |
|
| 14 |
Shows a simple user interface being updated by multiple threads. |
| 15 |
|
| 16 |
When the *Start Threads* button is pressed, the program starts three independent |
| 17 |
threads running. Each thread counts from 0 to 199, updating its own |
| 18 |
thread-specific trait, and performs a sleep of a thread-specific duration |
| 19 |
between each update. |
| 20 |
|
| 21 |
The *Start Threads* button is disabled while the threads are running, and |
| 22 |
becomes active again once all threads have finished running. |
| 23 |
""" |
| 24 |
|
| 25 |
from threading import Thread |
| 26 |
from time import sleep |
| 27 |
from traits.api import HasTraits, Int, Button |
| 28 |
from traitsui.api import View, Item, VGroup |
| 29 |
|
| 30 |
|
| 31 |
class ThreadDemo(HasTraits): |
| 32 |
|
| 33 |
# The thread specific counters: |
| 34 |
thread_0 = Int() |
| 35 |
thread_1 = Int() |
| 36 |
thread_2 = Int() |
| 37 |
|
| 38 |
# The button used to start the threads running: |
| 39 |
start = Button('Start Threads') |
| 40 |
|
| 41 |
# The count of how many threads ae currently running: |
| 42 |
running = Int() |
| 43 |
|
| 44 |
view = View( |
| 45 |
VGroup( |
| 46 |
Item('thread_0', style='readonly'), |
| 47 |
Item('thread_1', style='readonly'), |
| 48 |
Item('thread_2', style='readonly'), |
| 49 |
), |
| 50 |
'_', |
| 51 |
Item('start', show_label=False, enabled_when='running == 0'), |
| 52 |
resizable=True, |
| 53 |
width=250, |
| 54 |
title='Monitoring threads', |
| 55 |
) |
| 56 |
|
| 57 |
def _start_changed(self): |
| 58 |
for i in range(3): |
| 59 |
Thread( |
| 60 |
target=self.counter, |
| 61 |
args=('thread_%d' % i, (i * 10 + 10) / 1000.0), |
| 62 |
).start() |
| 63 |
|
| 64 |
def counter(self, name, interval): |
| 65 |
self.running += 1 |
| 66 |
count = 0 |
| 67 |
for i in range(200): |
| 68 |
setattr(self, name, count) |
| 69 |
count += 1 |
| 70 |
sleep(interval) |
| 71 |
self.running -= 1 |
| 72 |
|
| 73 |
|
| 74 |
# Create the demo: |
| 75 |
demo = ThreadDemo() |
| 76 |
|
| 77 |
# Run the demo (if invoked from the command line): |
| 78 |
if __name__ == '__main__': |
| 79 |
demo.configure_traits() |