Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 1 | # 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 | |
| 8 | import thread |
Jack Jansen | 8779787 | 2001-08-29 20:26:24 +0000 | [diff] [blame] | 9 | from test_support import verbose, TestSkipped |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 10 | |
| 11 | critical_section = thread.allocate_lock() |
| 12 | done = thread.allocate_lock() |
| 13 | |
| 14 | def 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 Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 24 | # 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 Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 32 | |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 33 | def test_main(): # magic name! see above |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 34 | global N, done |
Jack Jansen | 8779787 | 2001-08-29 20:26:24 +0000 | [diff] [blame] | 35 | import sys |
| 36 | for modname in sys.modules: |
| 37 | if modname.find('autotest') >= 0: |
| 38 | raise TestSkipped("can't run from autotest") |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 39 | done.acquire() |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 40 | for N in (20, 50) * 3: |
| 41 | if verbose: |
| 42 | print "Trying", N, "threads ...", |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 43 | for i in range(N): |
| 44 | thread.start_new_thread(task, ()) |
| 45 | done.acquire() |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 46 | if verbose: |
| 47 | print "OK." |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 48 | |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 49 | if __name__ == "__main__": |
| 50 | test_main() |