blob: 52301177de1efbcd5ba5f31ac41a927ddf0172fa [file] [log] [blame]
Skip Montanaro4533f602001-08-20 20:28:48 +00001# Very rudimentary test of threading module
2
3# Create a bunch of threads, let each do some work, wait until all are done
4
5from test_support import verbose
6import random
7import threading
8import time
9
Tim Peters02035bc2001-08-20 21:45:19 +000010# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
11# about 1 second per clump).
Skip Montanaro4533f602001-08-20 20:28:48 +000012numtasks = 10
13
14# no more than 3 of the 10 can run at once
15sema = threading.BoundedSemaphore(value=3)
16mutex = threading.RLock()
17running = 0
18
19class TestThread(threading.Thread):
20 def run(self):
21 global running
Tim Peters02035bc2001-08-20 21:45:19 +000022 delay = random.random() * 2
Skip Montanaro4533f602001-08-20 20:28:48 +000023 if verbose:
Tim Peters02035bc2001-08-20 21:45:19 +000024 print 'task', self.getName(), 'will run for', delay, 'sec'
Skip Montanaro4533f602001-08-20 20:28:48 +000025 sema.acquire()
26 mutex.acquire()
27 running = running + 1
28 if verbose:
29 print running, 'tasks are running'
30 mutex.release()
31 time.sleep(delay)
32 if verbose:
33 print 'task', self.getName(), 'done'
34 mutex.acquire()
35 running = running - 1
36 if verbose:
37 print self.getName(), 'is finished.', running, 'tasks are running'
38 mutex.release()
39 sema.release()
40
41threads = []
42def starttasks():
43 for i in range(numtasks):
44 t = TestThread(name="<thread %d>"%i)
45 threads.append(t)
46 t.start()
47
48starttasks()
49
Tim Peters02035bc2001-08-20 21:45:19 +000050if verbose:
51 print 'waiting for all tasks to complete'
Skip Montanaro4533f602001-08-20 20:28:48 +000052for t in threads:
53 t.join()
Tim Peters02035bc2001-08-20 21:45:19 +000054if verbose:
55 print 'all tasks done'