1 # Copyright 2013 The Chromium 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.
5 """Thread and ThreadGroup that reraise exceptions on the main thread."""
6 # pylint: disable=W0212
13 from pylib
.utils
import watchdog_timer
16 class TimeoutError(Exception):
17 """Module-specific timeout exception."""
21 def LogThreadStack(thread
):
22 """Log the stack for the given thread.
25 thread: a threading.Thread instance.
27 stack
= sys
._current
_frames
()[thread
.ident
]
28 logging
.critical('*' * 80)
29 logging
.critical('Stack dump for thread \'%s\'', thread
.name
)
30 logging
.critical('*' * 80)
31 for filename
, lineno
, name
, line
in traceback
.extract_stack(stack
):
32 logging
.critical('File: "%s", line %d, in %s', filename
, lineno
, name
)
34 logging
.critical(' %s', line
.strip())
35 logging
.critical('*' * 80)
38 class ReraiserThread(threading
.Thread
):
39 """Thread class that can reraise exceptions."""
41 def __init__(self
, func
, args
=None, kwargs
=None, name
=None):
45 func: callable to call on a new thread.
46 args: list of positional arguments for callable, defaults to empty.
47 kwargs: dictionary of keyword arguments for callable, defaults to empty.
48 name: thread name, defaults to Thread-N.
50 super(ReraiserThread
, self
).__init
__(name
=name
)
61 def ReraiseIfException(self
):
62 """Reraise exception if an exception was raised in the thread."""
64 raise self
._exc
_info
[0], self
._exc
_info
[1], self
._exc
_info
[2]
68 """Overrides Thread.run() to add support for reraising exceptions."""
70 self
._func
(*self
._args
, **self
._kwargs
)
72 self
._exc
_info
= sys
.exc_info()
76 class ReraiserThreadGroup(object):
77 """A group of ReraiserThread objects."""
79 def __init__(self
, threads
=None):
80 """Initialize thread group.
83 threads: a list of ReraiserThread objects; defaults to empty.
87 self
._threads
= threads
89 def Add(self
, thread
):
90 """Add a thread to the group.
93 thread: a ReraiserThread object.
95 self
._threads
.append(thread
)
98 """Start all threads."""
99 for thread
in self
._threads
:
102 def _JoinAll(self
, watcher
=watchdog_timer
.WatchdogTimer(None)):
103 """Join all threads without stack dumps.
105 Reraises exceptions raised by the child threads and supports breaking
106 immediately on exceptions raised on the main thread.
109 watcher: Watchdog object providing timeout, by default waits forever.
111 alive_threads
= self
._threads
[:]
113 for thread
in alive_threads
[:]:
114 if watcher
.IsTimedOut():
115 raise TimeoutError('Timed out waiting for %d of %d threads.' %
116 (len(alive_threads
), len(self
._threads
)))
117 # Allow the main thread to periodically check for interrupts.
119 if not thread
.isAlive():
120 alive_threads
.remove(thread
)
121 # All threads are allowed to complete before reraising exceptions.
122 for thread
in self
._threads
:
123 thread
.ReraiseIfException()
125 def JoinAll(self
, watcher
=watchdog_timer
.WatchdogTimer(None)):
128 Reraises exceptions raised by the child threads and supports breaking
129 immediately on exceptions raised on the main thread. Unfinished threads'
130 stacks will be logged on watchdog timeout.
133 watcher: Watchdog object providing timeout, by default waits forever.
136 self
._JoinAll
(watcher
)
138 for thread
in (t
for t
in self
._threads
if t
.isAlive()):
139 LogThreadStack(thread
)