blob: 46e405ab818dbd7932be6e8579c7b12fd3d3af97 [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
17
Guido van Rossum1bc535d2007-05-15 18:46:22 +000018def registerSignals(for_usr1, for_usr2, for_alrm):
Michael W. Hudson43220ea2004-08-03 14:37:14 +000019 usr1 = signal.signal(signal.SIGUSR1, for_usr1)
20 usr2 = signal.signal(signal.SIGUSR2, for_usr2)
21 alrm = signal.signal(signal.SIGALRM, for_alrm)
22 return usr1, usr2, alrm
23
24
Fred Drakedb390c12005-10-28 14:39:47 +000025# The signal handler. Just note that the signal occurred and
Michael W. Hudson43220ea2004-08-03 14:37:14 +000026# from who.
27def handle_signals(sig,frame):
Tim Peters6db15d72004-08-04 02:36:18 +000028 signal_blackboard[sig]['tripped'] += 1
Michael W. Hudson43220ea2004-08-03 14:37:14 +000029 signal_blackboard[sig]['tripped_by'] = thread.get_ident()
30
31# a function that will be spawned as a separate thread.
32def send_signals():
33 os.kill(process_pid, signal.SIGUSR1)
34 os.kill(process_pid, signal.SIGUSR2)
35 signalled_all.release()
36
37class ThreadSignals(unittest.TestCase):
Antoine Pitrou810023d2010-12-15 22:59:16 +000038
Michael W. Hudson43220ea2004-08-03 14:37:14 +000039 def test_signals(self):
Antoine Pitrou810023d2010-12-15 22:59:16 +000040 # Test signal handling semantics of threads.
41 # We spawn a thread, have the thread send two signals, and
42 # wait for it to finish. Check that we got both signals
43 # and that they were run by the main thread.
Michael W. Hudson43220ea2004-08-03 14:37:14 +000044 signalled_all.acquire()
45 self.spawnSignallingThread()
46 signalled_all.acquire()
47 # the signals that we asked the kernel to send
48 # will come back, but we don't know when.
49 # (it might even be after the thread exits
50 # and might be out of order.) If we haven't seen
51 # the signals yet, send yet another signal and
52 # wait for it return.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000053 if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
Michael W. Hudson43220ea2004-08-03 14:37:14 +000054 or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
Tim Peters6db15d72004-08-04 02:36:18 +000055 signal.alarm(1)
56 signal.pause()
57 signal.alarm(0)
Michael W. Hudson43220ea2004-08-03 14:37:14 +000058
59 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000060 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000061 thread.get_ident())
62 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000063 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000064 thread.get_ident())
Michael W. Hudson574a2512004-08-04 14:22:56 +000065 signalled_all.release()
Michael W. Hudson43220ea2004-08-03 14:37:14 +000066
67 def spawnSignallingThread(self):
68 thread.start_new_thread(send_signals, ())
Tim Peters6db15d72004-08-04 02:36:18 +000069
Antoine Pitrou810023d2010-12-15 22:59:16 +000070 def alarm_interrupt(self, sig, frame):
71 raise KeyboardInterrupt
72
73 def test_lock_acquire_interruption(self):
74 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
75 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +010076 # XXX this test can fail when the legacy (non-semaphore) implementation
77 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +000078 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
79 try:
80 lock = thread.allocate_lock()
81 lock.acquire()
82 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +010083 t1 = time.time()
84 self.assertRaises(KeyboardInterrupt, lock.acquire, timeout=5)
85 dt = time.time() - t1
86 # Checking that KeyboardInterrupt was raised is not sufficient.
87 # We want to assert that lock.acquire() was interrupted because
88 # of the signal, not that the signal handler was called immediately
89 # after timeout return of lock.acquire() (which can fool assertRaises).
90 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +000091 finally:
92 signal.signal(signal.SIGALRM, oldalrm)
93
94 def test_rlock_acquire_interruption(self):
95 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
96 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +010097 # XXX this test can fail when the legacy (non-semaphore) implementation
98 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +000099 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
100 try:
101 rlock = thread.RLock()
102 # For reentrant locks, the initial acquisition must be in another
103 # thread.
104 def other_thread():
105 rlock.acquire()
106 thread.start_new_thread(other_thread, ())
107 # Wait until we can't acquire it without blocking...
108 while rlock.acquire(blocking=False):
109 rlock.release()
110 time.sleep(0.01)
111 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100112 t1 = time.time()
113 self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5)
114 dt = time.time() - t1
115 # See rationale above in test_lock_acquire_interruption
116 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000117 finally:
118 signal.signal(signal.SIGALRM, oldalrm)
119
120 def acquire_retries_on_intr(self, lock):
121 self.sig_recvd = False
122 def my_handler(signal, frame):
123 self.sig_recvd = True
124 old_handler = signal.signal(signal.SIGUSR1, my_handler)
125 try:
126 def other_thread():
127 # Acquire the lock in a non-main thread, so this test works for
128 # RLocks.
129 lock.acquire()
130 # Wait until the main thread is blocked in the lock acquire, and
131 # then wake it up with this.
132 time.sleep(0.5)
133 os.kill(process_pid, signal.SIGUSR1)
134 # Let the main thread take the interrupt, handle it, and retry
135 # the lock acquisition. Then we'll let it run.
136 time.sleep(0.5)
137 lock.release()
138 thread.start_new_thread(other_thread, ())
139 # Wait until we can't acquire it without blocking...
140 while lock.acquire(blocking=False):
141 lock.release()
142 time.sleep(0.01)
143 result = lock.acquire() # Block while we receive a signal.
144 self.assertTrue(self.sig_recvd)
145 self.assertTrue(result)
146 finally:
147 signal.signal(signal.SIGUSR1, old_handler)
148
149 def test_lock_acquire_retries_on_intr(self):
150 self.acquire_retries_on_intr(thread.allocate_lock())
151
152 def test_rlock_acquire_retries_on_intr(self):
153 self.acquire_retries_on_intr(thread.RLock())
154
155 def test_interrupted_timed_acquire(self):
156 # Test to make sure we recompute lock acquisition timeouts when we
157 # receive a signal. Check this by repeatedly interrupting a lock
158 # acquire in the main thread, and make sure that the lock acquire times
159 # out after the right amount of time.
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000160 # NOTE: this test only behaves as expected if C signals get delivered
161 # to the main thread. Otherwise lock.acquire() itself doesn't get
162 # interrupted and the test trivially succeeds.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000163 self.start = None
164 self.end = None
165 self.sigs_recvd = 0
166 done = thread.allocate_lock()
167 done.acquire()
168 lock = thread.allocate_lock()
169 lock.acquire()
170 def my_handler(signum, frame):
171 self.sigs_recvd += 1
172 old_handler = signal.signal(signal.SIGUSR1, my_handler)
173 try:
174 def timed_acquire():
175 self.start = time.time()
176 lock.acquire(timeout=0.5)
177 self.end = time.time()
178 def send_signals():
179 for _ in range(40):
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000180 time.sleep(0.02)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000181 os.kill(process_pid, signal.SIGUSR1)
182 done.release()
183
184 # Send the signals from the non-main thread, since the main thread
185 # is the only one that can process signals.
186 thread.start_new_thread(send_signals, ())
187 timed_acquire()
188 # Wait for thread to finish
189 done.acquire()
190 # This allows for some timing and scheduling imprecision
191 self.assertLess(self.end - self.start, 2.0)
192 self.assertGreater(self.end - self.start, 0.3)
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000193 # If the signal is received several times before PyErr_CheckSignals()
Antoine Pitroud8f37ad2011-01-02 16:16:09 +0000194 # is called, the handler will get called less than 40 times. Just
195 # check it's been called at least once.
196 self.assertGreater(self.sigs_recvd, 0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000197 finally:
198 signal.signal(signal.SIGUSR1, old_handler)
199
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000200
201def test_main():
Michael W. Hudson574a2512004-08-04 14:22:56 +0000202 global signal_blackboard
Tim Petersd1b78272004-08-07 06:03:09 +0000203
Michael W. Hudson574a2512004-08-04 14:22:56 +0000204 signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
205 signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
206 signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
207
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000208 oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000209 try:
Michael W. Hudson574a2512004-08-04 14:22:56 +0000210 run_unittest(ThreadSignals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000211 finally:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000212 registerSignals(*oldsigs)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000213
214if __name__ == '__main__':
215 test_main()