1 # Very rudimentary test of thread module
3 # Create a bunch of threads, let each do some work, wait until all are done
5 from test
.test_support
import verbose
10 mutex
= thread
.allocate_lock()
11 rmutex
= thread
.allocate_lock() # for calls to random
13 done
= thread
.allocate_lock()
21 delay
= random
.random() * numtasks
24 print 'task', ident
, 'will run for', round(delay
, 1), 'sec'
27 print 'task', ident
, 'done'
36 global next_ident
, running
38 next_ident
= next_ident
+ 1
40 print 'creating task', next_ident
41 thread
.start_new_thread(task
, (next_ident
,))
45 for i
in range(numtasks
):
48 print 'waiting for all tasks to complete'
50 print 'all tasks done'
53 def __init__(self
, n
):
56 self
.checkin
= thread
.allocate_lock()
57 self
.checkout
= thread
.allocate_lock()
58 self
.checkout
.acquire()
61 checkin
, checkout
= self
.checkin
, self
.checkout
64 self
.waiting
= self
.waiting
+ 1
65 if self
.waiting
== self
.n
:
66 self
.waiting
= self
.n
- 1
72 self
.waiting
= self
.waiting
- 1
81 for i
in range(numtrips
):
83 # give it a good chance to enter the next
84 # barrier before the others are all out
89 delay
= random
.random() * numtasks
92 print 'task', ident
, 'will run for', round(delay
, 1), 'sec'
95 print 'task', ident
, 'entering barrier', i
98 print 'task', ident
, 'leaving barrier', i
101 # Must release mutex before releasing done, else the main thread can
102 # exit and set mutex to None as part of global teardown; then
103 # mutex.release() raises AttributeError.
104 finished
= running
== 0
109 print '\n*** Barrier Test ***'
111 raise ValueError, "'done' should have remained acquired"
112 bar
= barrier(numtasks
)
114 for i
in range(numtasks
):
115 thread
.start_new_thread(task2
, (i
,))
117 print 'all tasks done'
119 # not all platforms support changing thread stack size
120 print '\n*** Changing thread stack size ***'
121 if thread
.stack_size() != 0:
122 raise ValueError, "initial stack_size not 0"
125 if thread
.stack_size() != 0:
126 raise ValueError, "stack_size not reset to default"
128 from os
import name
as os_name
129 if os_name
in ("nt", "os2", "posix"):
133 thread
.stack_size(4096)
135 print 'caught expected ValueError setting stack_size(4096)'
138 print 'platform does not support changing thread stack size'
141 failed
= lambda s
, e
: s
!= e
142 fail_msg
= "stack_size(%d) failed - should succeed"
143 for tss
in (262144, 0x100000, 0):
144 thread
.stack_size(tss
)
145 if failed(thread
.stack_size(), tss
):
146 raise ValueError, fail_msg
% tss
147 print 'successfully set stack_size(%d)' % tss
149 for tss
in (262144, 0x100000):
150 print 'trying stack_size = %d' % tss
152 for i
in range(numtasks
):
155 print 'waiting for all tasks to complete'
157 print 'all tasks done'
159 # reset stack size to default