blob: f975a75e85d76c9f5fc5f5d5a0ca3173ecca045b [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 Stinnerd5c355c2011-04-30 14:53:09 +020017USING_PTHREAD_COND = (sys.thread_info.name == 'pthread'
18 and sys.thread_info.lock == 'mutex+cond')
Michael W. Hudson43220ea2004-08-03 14:37:14 +000019
Guido van Rossum1bc535d2007-05-15 18:46:22 +000020def registerSignals(for_usr1, for_usr2, for_alrm):
Michael W. Hudson43220ea2004-08-03 14:37:14 +000021 usr1 = signal.signal(signal.SIGUSR1, for_usr1)
22 usr2 = signal.signal(signal.SIGUSR2, for_usr2)
23 alrm = signal.signal(signal.SIGALRM, for_alrm)
24 return usr1, usr2, alrm
25
26
Fred Drakedb390c12005-10-28 14:39:47 +000027# The signal handler. Just note that the signal occurred and
Michael W. Hudson43220ea2004-08-03 14:37:14 +000028# from who.
29def handle_signals(sig,frame):
Tim Peters6db15d72004-08-04 02:36:18 +000030 signal_blackboard[sig]['tripped'] += 1
Michael W. Hudson43220ea2004-08-03 14:37:14 +000031 signal_blackboard[sig]['tripped_by'] = thread.get_ident()
32
33# a function that will be spawned as a separate thread.
34def send_signals():
35 os.kill(process_pid, signal.SIGUSR1)
36 os.kill(process_pid, signal.SIGUSR2)
37 signalled_all.release()
38
39class ThreadSignals(unittest.TestCase):
Antoine Pitrou810023d2010-12-15 22:59:16 +000040
Michael W. Hudson43220ea2004-08-03 14:37:14 +000041 def test_signals(self):
Antoine Pitrou810023d2010-12-15 22:59:16 +000042 # Test signal handling semantics of threads.
43 # We spawn a thread, have the thread send two signals, and
44 # wait for it to finish. Check that we got both signals
45 # and that they were run by the main thread.
Michael W. Hudson43220ea2004-08-03 14:37:14 +000046 signalled_all.acquire()
47 self.spawnSignallingThread()
48 signalled_all.acquire()
49 # the signals that we asked the kernel to send
50 # will come back, but we don't know when.
51 # (it might even be after the thread exits
52 # and might be out of order.) If we haven't seen
53 # the signals yet, send yet another signal and
54 # wait for it return.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000055 if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
Michael W. Hudson43220ea2004-08-03 14:37:14 +000056 or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
Tim Peters6db15d72004-08-04 02:36:18 +000057 signal.alarm(1)
58 signal.pause()
59 signal.alarm(0)
Michael W. Hudson43220ea2004-08-03 14:37:14 +000060
61 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000062 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000063 thread.get_ident())
64 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000065 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000066 thread.get_ident())
Michael W. Hudson574a2512004-08-04 14:22:56 +000067 signalled_all.release()
Michael W. Hudson43220ea2004-08-03 14:37:14 +000068
69 def spawnSignallingThread(self):
70 thread.start_new_thread(send_signals, ())
Tim Peters6db15d72004-08-04 02:36:18 +000071
Antoine Pitrou810023d2010-12-15 22:59:16 +000072 def alarm_interrupt(self, sig, frame):
73 raise KeyboardInterrupt
74
Victor Stinner754851f2011-04-19 23:58:51 +020075 @unittest.skipIf(USING_PTHREAD_COND,
76 'POSIX condition variables cannot be interrupted')
Antoine Pitrou810023d2010-12-15 22:59:16 +000077 def test_lock_acquire_interruption(self):
78 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
79 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +010080 # XXX this test can fail when the legacy (non-semaphore) implementation
81 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +000082 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
83 try:
84 lock = thread.allocate_lock()
85 lock.acquire()
86 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +010087 t1 = time.time()
88 self.assertRaises(KeyboardInterrupt, lock.acquire, timeout=5)
89 dt = time.time() - t1
90 # Checking that KeyboardInterrupt was raised is not sufficient.
91 # We want to assert that lock.acquire() was interrupted because
92 # of the signal, not that the signal handler was called immediately
93 # after timeout return of lock.acquire() (which can fool assertRaises).
94 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +000095 finally:
96 signal.signal(signal.SIGALRM, oldalrm)
97
Victor Stinner754851f2011-04-19 23:58:51 +020098 @unittest.skipIf(USING_PTHREAD_COND,
99 'POSIX condition variables cannot be interrupted')
Antoine Pitrou810023d2010-12-15 22:59:16 +0000100 def test_rlock_acquire_interruption(self):
101 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
102 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100103 # XXX this test can fail when the legacy (non-semaphore) implementation
104 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000105 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
106 try:
107 rlock = thread.RLock()
108 # For reentrant locks, the initial acquisition must be in another
109 # thread.
110 def other_thread():
111 rlock.acquire()
112 thread.start_new_thread(other_thread, ())
113 # Wait until we can't acquire it without blocking...
114 while rlock.acquire(blocking=False):
115 rlock.release()
116 time.sleep(0.01)
117 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100118 t1 = time.time()
119 self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5)
120 dt = time.time() - t1
121 # See rationale above in test_lock_acquire_interruption
122 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000123 finally:
124 signal.signal(signal.SIGALRM, oldalrm)
125
126 def acquire_retries_on_intr(self, lock):
127 self.sig_recvd = False
128 def my_handler(signal, frame):
129 self.sig_recvd = True
130 old_handler = signal.signal(signal.SIGUSR1, my_handler)
131 try:
132 def other_thread():
133 # Acquire the lock in a non-main thread, so this test works for
134 # RLocks.
135 lock.acquire()
136 # Wait until the main thread is blocked in the lock acquire, and
137 # then wake it up with this.
138 time.sleep(0.5)
139 os.kill(process_pid, signal.SIGUSR1)
140 # Let the main thread take the interrupt, handle it, and retry
141 # the lock acquisition. Then we'll let it run.
142 time.sleep(0.5)
143 lock.release()
144 thread.start_new_thread(other_thread, ())
145 # Wait until we can't acquire it without blocking...
146 while lock.acquire(blocking=False):
147 lock.release()
148 time.sleep(0.01)
149 result = lock.acquire() # Block while we receive a signal.
150 self.assertTrue(self.sig_recvd)
151 self.assertTrue(result)
152 finally:
153 signal.signal(signal.SIGUSR1, old_handler)
154
155 def test_lock_acquire_retries_on_intr(self):
156 self.acquire_retries_on_intr(thread.allocate_lock())
157
158 def test_rlock_acquire_retries_on_intr(self):
159 self.acquire_retries_on_intr(thread.RLock())
160
161 def test_interrupted_timed_acquire(self):
162 # Test to make sure we recompute lock acquisition timeouts when we
163 # receive a signal. Check this by repeatedly interrupting a lock
164 # acquire in the main thread, and make sure that the lock acquire times
165 # out after the right amount of time.
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000166 # NOTE: this test only behaves as expected if C signals get delivered
167 # to the main thread. Otherwise lock.acquire() itself doesn't get
168 # interrupted and the test trivially succeeds.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000169 self.start = None
170 self.end = None
171 self.sigs_recvd = 0
172 done = thread.allocate_lock()
173 done.acquire()
174 lock = thread.allocate_lock()
175 lock.acquire()
176 def my_handler(signum, frame):
177 self.sigs_recvd += 1
178 old_handler = signal.signal(signal.SIGUSR1, my_handler)
179 try:
180 def timed_acquire():
181 self.start = time.time()
182 lock.acquire(timeout=0.5)
183 self.end = time.time()
184 def send_signals():
185 for _ in range(40):
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000186 time.sleep(0.02)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000187 os.kill(process_pid, signal.SIGUSR1)
188 done.release()
189
190 # Send the signals from the non-main thread, since the main thread
191 # is the only one that can process signals.
192 thread.start_new_thread(send_signals, ())
193 timed_acquire()
194 # Wait for thread to finish
195 done.acquire()
196 # This allows for some timing and scheduling imprecision
197 self.assertLess(self.end - self.start, 2.0)
198 self.assertGreater(self.end - self.start, 0.3)
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000199 # If the signal is received several times before PyErr_CheckSignals()
Antoine Pitroud8f37ad2011-01-02 16:16:09 +0000200 # is called, the handler will get called less than 40 times. Just
201 # check it's been called at least once.
202 self.assertGreater(self.sigs_recvd, 0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000203 finally:
204 signal.signal(signal.SIGUSR1, old_handler)
205
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000206
207def test_main():
Michael W. Hudson574a2512004-08-04 14:22:56 +0000208 global signal_blackboard
Tim Petersd1b78272004-08-07 06:03:09 +0000209
Michael W. Hudson574a2512004-08-04 14:22:56 +0000210 signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
211 signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
212 signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
213
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000214 oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000215 try:
Michael W. Hudson574a2512004-08-04 14:22:56 +0000216 run_unittest(ThreadSignals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000217 finally:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000218 registerSignals(*oldsigs)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000219
220if __name__ == '__main__':
221 test_main()