blob: b0bc6072851177aa852bdf5991489aa2f9559ded [file] [log] [blame]
Michael W. Hudson43220ea2004-08-03 14:37:14 +00001"""PyUnit testing that threads honor our signal semantics"""
2
3import unittest
Michael W. Hudson43220ea2004-08-03 14:37:14 +00004import signal
5import os
Fred Drake48187482004-08-03 16:14:13 +00006import sys
Victor Stinner45df8202010-04-28 22:31:17 +00007from test.support import run_unittest, import_module
8thread = import_module('_thread')
Antoine Pitrou810023d2010-12-15 22:59:16 +00009import time
Michael W. Hudson43220ea2004-08-03 14:37:14 +000010
Benjamin Petersone549ead2009-03-28 21:42:05 +000011if sys.platform[:3] in ('win', 'os2') or sys.platform=='riscos':
12 raise unittest.SkipTest("Can't test signal on %s" % sys.platform)
Michael W. Hudson34fba3b2004-08-03 15:35:29 +000013
Michael W. Hudson43220ea2004-08-03 14:37:14 +000014process_pid = os.getpid()
15signalled_all=thread.allocate_lock()
16
Victor Stinner754851f2011-04-19 23:58:51 +020017info = thread.info()
18USING_PTHREAD_COND = (info['name'] == 'pthread'
19 and info['lock_implementation'] == 'mutex+cond')
Michael W. Hudson43220ea2004-08-03 14:37:14 +000020
Guido van Rossum1bc535d2007-05-15 18:46:22 +000021def registerSignals(for_usr1, for_usr2, for_alrm):
Michael W. Hudson43220ea2004-08-03 14:37:14 +000022 usr1 = signal.signal(signal.SIGUSR1, for_usr1)
23 usr2 = signal.signal(signal.SIGUSR2, for_usr2)
24 alrm = signal.signal(signal.SIGALRM, for_alrm)
25 return usr1, usr2, alrm
26
27
Fred Drakedb390c12005-10-28 14:39:47 +000028# The signal handler. Just note that the signal occurred and
Michael W. Hudson43220ea2004-08-03 14:37:14 +000029# from who.
30def handle_signals(sig,frame):
Tim Peters6db15d72004-08-04 02:36:18 +000031 signal_blackboard[sig]['tripped'] += 1
Michael W. Hudson43220ea2004-08-03 14:37:14 +000032 signal_blackboard[sig]['tripped_by'] = thread.get_ident()
33
34# a function that will be spawned as a separate thread.
35def send_signals():
36 os.kill(process_pid, signal.SIGUSR1)
37 os.kill(process_pid, signal.SIGUSR2)
38 signalled_all.release()
39
40class ThreadSignals(unittest.TestCase):
Antoine Pitrou810023d2010-12-15 22:59:16 +000041
Michael W. Hudson43220ea2004-08-03 14:37:14 +000042 def test_signals(self):
Antoine Pitrou810023d2010-12-15 22:59:16 +000043 # Test signal handling semantics of threads.
44 # We spawn a thread, have the thread send two signals, and
45 # wait for it to finish. Check that we got both signals
46 # and that they were run by the main thread.
Michael W. Hudson43220ea2004-08-03 14:37:14 +000047 signalled_all.acquire()
48 self.spawnSignallingThread()
49 signalled_all.acquire()
50 # the signals that we asked the kernel to send
51 # will come back, but we don't know when.
52 # (it might even be after the thread exits
53 # and might be out of order.) If we haven't seen
54 # the signals yet, send yet another signal and
55 # wait for it return.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000056 if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
Michael W. Hudson43220ea2004-08-03 14:37:14 +000057 or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
Tim Peters6db15d72004-08-04 02:36:18 +000058 signal.alarm(1)
59 signal.pause()
60 signal.alarm(0)
Michael W. Hudson43220ea2004-08-03 14:37:14 +000061
62 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000063 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000064 thread.get_ident())
65 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000066 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000067 thread.get_ident())
Michael W. Hudson574a2512004-08-04 14:22:56 +000068 signalled_all.release()
Michael W. Hudson43220ea2004-08-03 14:37:14 +000069
70 def spawnSignallingThread(self):
71 thread.start_new_thread(send_signals, ())
Tim Peters6db15d72004-08-04 02:36:18 +000072
Antoine Pitrou810023d2010-12-15 22:59:16 +000073 def alarm_interrupt(self, sig, frame):
74 raise KeyboardInterrupt
75
Victor Stinner754851f2011-04-19 23:58:51 +020076 @unittest.skipIf(USING_PTHREAD_COND,
77 'POSIX condition variables cannot be interrupted')
Antoine Pitrou810023d2010-12-15 22:59:16 +000078 def test_lock_acquire_interruption(self):
79 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
80 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +010081 # XXX this test can fail when the legacy (non-semaphore) implementation
82 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +000083 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
84 try:
85 lock = thread.allocate_lock()
86 lock.acquire()
87 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +010088 t1 = time.time()
89 self.assertRaises(KeyboardInterrupt, lock.acquire, timeout=5)
90 dt = time.time() - t1
91 # Checking that KeyboardInterrupt was raised is not sufficient.
92 # We want to assert that lock.acquire() was interrupted because
93 # of the signal, not that the signal handler was called immediately
94 # after timeout return of lock.acquire() (which can fool assertRaises).
95 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +000096 finally:
97 signal.signal(signal.SIGALRM, oldalrm)
98
Victor Stinner754851f2011-04-19 23:58:51 +020099 @unittest.skipIf(USING_PTHREAD_COND,
100 'POSIX condition variables cannot be interrupted')
Antoine Pitrou810023d2010-12-15 22:59:16 +0000101 def test_rlock_acquire_interruption(self):
102 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
103 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100104 # XXX this test can fail when the legacy (non-semaphore) implementation
105 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000106 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
107 try:
108 rlock = thread.RLock()
109 # For reentrant locks, the initial acquisition must be in another
110 # thread.
111 def other_thread():
112 rlock.acquire()
113 thread.start_new_thread(other_thread, ())
114 # Wait until we can't acquire it without blocking...
115 while rlock.acquire(blocking=False):
116 rlock.release()
117 time.sleep(0.01)
118 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100119 t1 = time.time()
120 self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5)
121 dt = time.time() - t1
122 # See rationale above in test_lock_acquire_interruption
123 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000124 finally:
125 signal.signal(signal.SIGALRM, oldalrm)
126
127 def acquire_retries_on_intr(self, lock):
128 self.sig_recvd = False
129 def my_handler(signal, frame):
130 self.sig_recvd = True
131 old_handler = signal.signal(signal.SIGUSR1, my_handler)
132 try:
133 def other_thread():
134 # Acquire the lock in a non-main thread, so this test works for
135 # RLocks.
136 lock.acquire()
137 # Wait until the main thread is blocked in the lock acquire, and
138 # then wake it up with this.
139 time.sleep(0.5)
140 os.kill(process_pid, signal.SIGUSR1)
141 # Let the main thread take the interrupt, handle it, and retry
142 # the lock acquisition. Then we'll let it run.
143 time.sleep(0.5)
144 lock.release()
145 thread.start_new_thread(other_thread, ())
146 # Wait until we can't acquire it without blocking...
147 while lock.acquire(blocking=False):
148 lock.release()
149 time.sleep(0.01)
150 result = lock.acquire() # Block while we receive a signal.
151 self.assertTrue(self.sig_recvd)
152 self.assertTrue(result)
153 finally:
154 signal.signal(signal.SIGUSR1, old_handler)
155
156 def test_lock_acquire_retries_on_intr(self):
157 self.acquire_retries_on_intr(thread.allocate_lock())
158
159 def test_rlock_acquire_retries_on_intr(self):
160 self.acquire_retries_on_intr(thread.RLock())
161
162 def test_interrupted_timed_acquire(self):
163 # Test to make sure we recompute lock acquisition timeouts when we
164 # receive a signal. Check this by repeatedly interrupting a lock
165 # acquire in the main thread, and make sure that the lock acquire times
166 # out after the right amount of time.
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000167 # NOTE: this test only behaves as expected if C signals get delivered
168 # to the main thread. Otherwise lock.acquire() itself doesn't get
169 # interrupted and the test trivially succeeds.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000170 self.start = None
171 self.end = None
172 self.sigs_recvd = 0
173 done = thread.allocate_lock()
174 done.acquire()
175 lock = thread.allocate_lock()
176 lock.acquire()
177 def my_handler(signum, frame):
178 self.sigs_recvd += 1
179 old_handler = signal.signal(signal.SIGUSR1, my_handler)
180 try:
181 def timed_acquire():
182 self.start = time.time()
183 lock.acquire(timeout=0.5)
184 self.end = time.time()
185 def send_signals():
186 for _ in range(40):
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000187 time.sleep(0.02)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000188 os.kill(process_pid, signal.SIGUSR1)
189 done.release()
190
191 # Send the signals from the non-main thread, since the main thread
192 # is the only one that can process signals.
193 thread.start_new_thread(send_signals, ())
194 timed_acquire()
195 # Wait for thread to finish
196 done.acquire()
197 # This allows for some timing and scheduling imprecision
198 self.assertLess(self.end - self.start, 2.0)
199 self.assertGreater(self.end - self.start, 0.3)
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000200 # If the signal is received several times before PyErr_CheckSignals()
Antoine Pitroud8f37ad2011-01-02 16:16:09 +0000201 # is called, the handler will get called less than 40 times. Just
202 # check it's been called at least once.
203 self.assertGreater(self.sigs_recvd, 0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000204 finally:
205 signal.signal(signal.SIGUSR1, old_handler)
206
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000207
208def test_main():
Michael W. Hudson574a2512004-08-04 14:22:56 +0000209 global signal_blackboard
Tim Petersd1b78272004-08-07 06:03:09 +0000210
Michael W. Hudson574a2512004-08-04 14:22:56 +0000211 signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
212 signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
213 signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
214
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000215 oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000216 try:
Michael W. Hudson574a2512004-08-04 14:22:56 +0000217 run_unittest(ThreadSignals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000218 finally:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000219 registerSignals(*oldsigs)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000220
221if __name__ == '__main__':
222 test_main()