blob: f1650c3a890836353e611c8bda41c0b1cdb92ab4 [file] [log] [blame]
Craig Harrisone3ea8f22012-10-01 13:55:21 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import threading
6
7
8class ControlledStressor(threading.Thread):
9 def __init__(self, stressor):
10 """Run a stressor callable in a threaded loop on demand.
11
12 Creates a new thread and runs |stressor| in a loop until told to stop.
13
14 Args:
15 stressor: callable which performs a single stress event
16 """
17 super(ControlledStressor, self).__init__()
18 self.daemon = True
19 self._complete = threading.Event()
20 self._stressor = stressor
21
22
23 def run(self):
24 """Overloaded from threading.Thread."""
25 while not self._complete.is_set():
26 self._stressor()
27
28
29 def start(self):
30 """Start applying the stressor."""
31 self._complete.clear()
32 super(ControlledStressor, self).start()
33
34
35 def stop(self, timeout=45):
36 """Stop applying the stressor.
37
38 Args:
39 timeout: maximum time to wait for a single run of the stressor to
40 complete, defaults to 45 seconds."""
41 self._complete.set()
42 self.join(timeout)
43
44
45class CountedStressor(threading.Thread):
46 def __init__(self, stressor):
47 """Run a stressor callable in a threaded loop a given number of times.
48
49 Args:
50 stressor: callable which performs a single stress event
51 """
52 super(CountedStressor, self).__init__()
53 self.daemon = True
54 self._stressor = stressor
55
56
57 def run(self):
58 """Overloaded from threading.Thread."""
59 for i in xrange(self._count):
60 self._stressor()
61
62
63 def start(self, count):
64 """Apply the stressor a given number of times.
65
66 Args:
67 count: number of times to apply the stressor
68 """
69 self._count = count
70 super(CountedStressor, self).start()
71
72
73 def wait(self, timeout=None):
74 """Wait until the stressor completes.
75
76 Args:
77 timeout: maximum time for the thread to complete, by default never
78 times out.
79 """
80 self.join(timeout)