blob: f93dd772555bbffbd12c3350d7ea74c450ae8769 [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 Stinnerff40ecd2017-09-14 13:07:24 -07007from test import support
8thread = support.import_module('_thread')
Antoine Pitrou810023d2010-12-15 22:59:16 +00009import time
Michael W. Hudson43220ea2004-08-03 14:37:14 +000010
Christian Heimesde0b9622012-11-19 00:59:39 +010011if (sys.platform[:3] == 'win'):
Benjamin Petersone549ead2009-03-28 21:42:05 +000012 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):
Victor Stinnerff40ecd2017-09-14 13:07:24 -070042 with support.wait_threads_exit():
43 # 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.
47 signalled_all.acquire()
48 self.spawnSignallingThread()
49 signalled_all.acquire()
50
Michael W. Hudson43220ea2004-08-03 14:37:14 +000051 # the signals that we asked the kernel to send
52 # will come back, but we don't know when.
53 # (it might even be after the thread exits
54 # and might be out of order.) If we haven't seen
55 # the signals yet, send yet another signal and
56 # wait for it return.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000057 if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
Michael W. Hudson43220ea2004-08-03 14:37:14 +000058 or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
Tim Peters6db15d72004-08-04 02:36:18 +000059 signal.alarm(1)
60 signal.pause()
61 signal.alarm(0)
Michael W. Hudson43220ea2004-08-03 14:37:14 +000062
63 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000064 self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000065 thread.get_ident())
66 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
Tim Peters6db15d72004-08-04 02:36:18 +000067 self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
Michael W. Hudson43220ea2004-08-03 14:37:14 +000068 thread.get_ident())
Michael W. Hudson574a2512004-08-04 14:22:56 +000069 signalled_all.release()
Michael W. Hudson43220ea2004-08-03 14:37:14 +000070
71 def spawnSignallingThread(self):
72 thread.start_new_thread(send_signals, ())
Tim Peters6db15d72004-08-04 02:36:18 +000073
Antoine Pitrou810023d2010-12-15 22:59:16 +000074 def alarm_interrupt(self, sig, frame):
75 raise KeyboardInterrupt
76
Victor Stinner754851f2011-04-19 23:58:51 +020077 @unittest.skipIf(USING_PTHREAD_COND,
78 'POSIX condition variables cannot be interrupted')
Victor Stinner7d02d502014-02-18 09:19:48 +010079 # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD
80 @unittest.skipIf(sys.platform.startswith('openbsd'),
81 'lock cannot be interrupted on OpenBSD')
Antoine Pitrou810023d2010-12-15 22:59:16 +000082 def test_lock_acquire_interruption(self):
83 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
84 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +010085 # XXX this test can fail when the legacy (non-semaphore) implementation
86 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +000087 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
88 try:
89 lock = thread.allocate_lock()
90 lock.acquire()
91 signal.alarm(1)
Antoine Pitroud3cccd22011-03-13 19:14:21 +010092 t1 = time.time()
93 self.assertRaises(KeyboardInterrupt, lock.acquire, timeout=5)
94 dt = time.time() - t1
95 # Checking that KeyboardInterrupt was raised is not sufficient.
96 # We want to assert that lock.acquire() was interrupted because
97 # of the signal, not that the signal handler was called immediately
98 # after timeout return of lock.acquire() (which can fool assertRaises).
99 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000100 finally:
101 signal.signal(signal.SIGALRM, oldalrm)
102
Victor Stinner754851f2011-04-19 23:58:51 +0200103 @unittest.skipIf(USING_PTHREAD_COND,
104 'POSIX condition variables cannot be interrupted')
Victor Stinner7d02d502014-02-18 09:19:48 +0100105 # Issue #20564: sem_timedwait() cannot be interrupted on OpenBSD
106 @unittest.skipIf(sys.platform.startswith('openbsd'),
107 'lock cannot be interrupted on OpenBSD')
Antoine Pitrou810023d2010-12-15 22:59:16 +0000108 def test_rlock_acquire_interruption(self):
109 # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
110 # in a deadlock.
Antoine Pitroud3cccd22011-03-13 19:14:21 +0100111 # XXX this test can fail when the legacy (non-semaphore) implementation
112 # of locks is used in thread_pthread.h, see issue #11223.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000113 oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
114 try:
115 rlock = thread.RLock()
116 # For reentrant locks, the initial acquisition must be in another
117 # thread.
118 def other_thread():
119 rlock.acquire()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700120
121 with support.wait_threads_exit():
122 thread.start_new_thread(other_thread, ())
123 # Wait until we can't acquire it without blocking...
124 while rlock.acquire(blocking=False):
125 rlock.release()
126 time.sleep(0.01)
127 signal.alarm(1)
128 t1 = time.time()
129 self.assertRaises(KeyboardInterrupt, rlock.acquire, timeout=5)
130 dt = time.time() - t1
131 # See rationale above in test_lock_acquire_interruption
132 self.assertLess(dt, 3.0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000133 finally:
134 signal.signal(signal.SIGALRM, oldalrm)
135
136 def acquire_retries_on_intr(self, lock):
137 self.sig_recvd = False
138 def my_handler(signal, frame):
139 self.sig_recvd = True
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700140
Antoine Pitrou810023d2010-12-15 22:59:16 +0000141 old_handler = signal.signal(signal.SIGUSR1, my_handler)
142 try:
143 def other_thread():
144 # Acquire the lock in a non-main thread, so this test works for
145 # RLocks.
146 lock.acquire()
147 # Wait until the main thread is blocked in the lock acquire, and
148 # then wake it up with this.
149 time.sleep(0.5)
150 os.kill(process_pid, signal.SIGUSR1)
151 # Let the main thread take the interrupt, handle it, and retry
152 # the lock acquisition. Then we'll let it run.
153 time.sleep(0.5)
154 lock.release()
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700155
156 with support.wait_threads_exit():
157 thread.start_new_thread(other_thread, ())
158 # Wait until we can't acquire it without blocking...
159 while lock.acquire(blocking=False):
160 lock.release()
161 time.sleep(0.01)
162 result = lock.acquire() # Block while we receive a signal.
163 self.assertTrue(self.sig_recvd)
164 self.assertTrue(result)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000165 finally:
166 signal.signal(signal.SIGUSR1, old_handler)
167
168 def test_lock_acquire_retries_on_intr(self):
169 self.acquire_retries_on_intr(thread.allocate_lock())
170
171 def test_rlock_acquire_retries_on_intr(self):
172 self.acquire_retries_on_intr(thread.RLock())
173
174 def test_interrupted_timed_acquire(self):
175 # Test to make sure we recompute lock acquisition timeouts when we
176 # receive a signal. Check this by repeatedly interrupting a lock
177 # acquire in the main thread, and make sure that the lock acquire times
178 # out after the right amount of time.
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000179 # NOTE: this test only behaves as expected if C signals get delivered
180 # to the main thread. Otherwise lock.acquire() itself doesn't get
181 # interrupted and the test trivially succeeds.
Antoine Pitrou810023d2010-12-15 22:59:16 +0000182 self.start = None
183 self.end = None
184 self.sigs_recvd = 0
185 done = thread.allocate_lock()
186 done.acquire()
187 lock = thread.allocate_lock()
188 lock.acquire()
189 def my_handler(signum, frame):
190 self.sigs_recvd += 1
191 old_handler = signal.signal(signal.SIGUSR1, my_handler)
192 try:
193 def timed_acquire():
194 self.start = time.time()
195 lock.acquire(timeout=0.5)
196 self.end = time.time()
197 def send_signals():
198 for _ in range(40):
Antoine Pitrou4fef5552010-12-15 23:38:50 +0000199 time.sleep(0.02)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000200 os.kill(process_pid, signal.SIGUSR1)
201 done.release()
202
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700203 with support.wait_threads_exit():
204 # Send the signals from the non-main thread, since the main thread
205 # is the only one that can process signals.
206 thread.start_new_thread(send_signals, ())
207 timed_acquire()
208 # Wait for thread to finish
209 done.acquire()
210 # This allows for some timing and scheduling imprecision
211 self.assertLess(self.end - self.start, 2.0)
212 self.assertGreater(self.end - self.start, 0.3)
213 # If the signal is received several times before PyErr_CheckSignals()
214 # is called, the handler will get called less than 40 times. Just
215 # check it's been called at least once.
216 self.assertGreater(self.sigs_recvd, 0)
Antoine Pitrou810023d2010-12-15 22:59:16 +0000217 finally:
218 signal.signal(signal.SIGUSR1, old_handler)
219
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000220
221def test_main():
Michael W. Hudson574a2512004-08-04 14:22:56 +0000222 global signal_blackboard
Tim Petersd1b78272004-08-07 06:03:09 +0000223
Michael W. Hudson574a2512004-08-04 14:22:56 +0000224 signal_blackboard = { signal.SIGUSR1 : {'tripped': 0, 'tripped_by': 0 },
225 signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
226 signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
227
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000228 oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000229 try:
Victor Stinnerff40ecd2017-09-14 13:07:24 -0700230 support.run_unittest(ThreadSignals)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000231 finally:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000232 registerSignals(*oldsigs)
Michael W. Hudson43220ea2004-08-03 14:37:14 +0000233
234if __name__ == '__main__':
235 test_main()