blob: e022c5fe924118de39498fe0e2c0d6becfd0b566 [file] [log] [blame]
Tim Petersaa222232001-05-22 09:34:27 +00001# This is a variant of the very old (early 90's) file
2# Demo/threads/bug.py. It simply provokes a number of threads into
3# trying to import the same module "at the same time".
4# There are no pleasant failure modes -- most likely is that Python
5# complains several times about module random having no attribute
6# randrange, and then Python hangs.
7
8import thread
Jack Jansen87797872001-08-29 20:26:24 +00009from test_support import verbose, TestSkipped
Tim Petersaa222232001-05-22 09:34:27 +000010
11critical_section = thread.allocate_lock()
12done = thread.allocate_lock()
13
14def task():
15 global N, critical_section, done
16 import random
17 x = random.randrange(1, 3)
18 critical_section.acquire()
19 N -= 1
20 if N == 0:
21 done.release()
22 critical_section.release()
23
Tim Petersd9742212001-05-22 18:28:25 +000024# Tricky: When regrtest imports this module, the thread running regrtest
25# grabs the import lock and won't let go of it until this module returns.
26# All other threads attempting an import hang for the duration. Since
27# this test spawns threads that do little *but* import, we can't do that
28# successfully until after this module finishes importing and regrtest
29# regains control. To make this work, a special case was added to
30# regrtest to invoke a module's "test_main" function (if any) after
31# importing it.
Tim Petersaa222232001-05-22 09:34:27 +000032
Tim Petersd9742212001-05-22 18:28:25 +000033def test_main(): # magic name! see above
Tim Petersaa222232001-05-22 09:34:27 +000034 global N, done
Tim Peters69232342001-08-30 05:16:13 +000035
36 import imp
37 if imp.lock_held():
38 # This triggers on, e.g., from test import autotest.
39 raise TestSkipped("can't run when import lock is held")
40
Tim Petersaa222232001-05-22 09:34:27 +000041 done.acquire()
Tim Petersd9742212001-05-22 18:28:25 +000042 for N in (20, 50) * 3:
43 if verbose:
44 print "Trying", N, "threads ...",
Tim Petersaa222232001-05-22 09:34:27 +000045 for i in range(N):
46 thread.start_new_thread(task, ())
47 done.acquire()
Tim Petersd9742212001-05-22 18:28:25 +000048 if verbose:
49 print "OK."
Tim Petersaa222232001-05-22 09:34:27 +000050
Tim Petersd9742212001-05-22 18:28:25 +000051if __name__ == "__main__":
52 test_main()