Guido van Rossum | cc54417 | 1994-04-14 20:28:41 +0000 | [diff] [blame] | 1 | # Very rudimentary test of thread module |
| 2 | |
| 3 | # Create a bunch of threads, let each do some work, wait until all are done |
| 4 | |
| 5 | import whrandom |
| 6 | import thread |
| 7 | import time |
| 8 | |
| 9 | mutex = thread.allocate_lock() |
| 10 | running = 0 |
| 11 | done = thread.allocate_lock() |
| 12 | done.acquire() |
| 13 | |
| 14 | def task(ident): |
| 15 | global running |
| 16 | delay = whrandom.random() * 10 |
| 17 | print 'task', ident, 'will run for', delay, 'sec' |
| 18 | time.sleep(delay) |
| 19 | print 'task', ident, 'done' |
| 20 | mutex.acquire() |
| 21 | running = running - 1 |
| 22 | if running == 0: |
| 23 | done.release() |
| 24 | mutex.release() |
| 25 | |
| 26 | next_ident = 0 |
| 27 | def newtask(): |
| 28 | global next_ident, running |
| 29 | mutex.acquire() |
| 30 | next_ident = next_ident + 1 |
| 31 | print 'creating task', next_ident |
| 32 | thread.start_new_thread(task, (next_ident,)) |
| 33 | running = running + 1 |
| 34 | mutex.release() |
| 35 | |
| 36 | for i in range(10): |
| 37 | newtask() |
| 38 | |
| 39 | print 'waiting for all tasks to complete' |
| 40 | done.acquire() |
| 41 | print 'all tasks done' |