File tree Expand file tree Collapse file tree 3 files changed +105
-0
lines changed
Expand file tree Collapse file tree 3 files changed +105
-0
lines changed Original file line number Diff line number Diff line change 1+ # test using lock to coordinate access to global mutable objects
2+ #
3+ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4+
5+ import _thread
6+
7+ def fac (n ):
8+ x = 1
9+ for i in range (1 , n + 1 ):
10+ x *= i
11+ return x
12+
13+ def thread_entry ():
14+ while True :
15+ with jobs_lock :
16+ try :
17+ f , arg = jobs .pop (0 )
18+ except IndexError :
19+ return
20+ ans = f (arg )
21+ with output_lock :
22+ output .append ((arg , ans ))
23+
24+ # create a list of jobs
25+ jobs = [(fac , i ) for i in range (20 , 80 )]
26+ jobs_lock = _thread .allocate_lock ()
27+ n_jobs = len (jobs )
28+
29+ # create a list to store the results
30+ output = []
31+ output_lock = _thread .allocate_lock ()
32+
33+ # spawn threads to do the jobs
34+ for i in range (4 ):
35+ _thread .start_new_thread (thread_entry , ())
36+
37+ # wait for the jobs to complete
38+ while True :
39+ with jobs_lock :
40+ if len (output ) == n_jobs :
41+ break
42+
43+ # sort and print the results
44+ output .sort (key = lambda x : x [0 ])
45+ for arg , ans in output :
46+ print (arg , ans )
Original file line number Diff line number Diff line change 1+ # test setting the thread stack size
2+ #
3+ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4+
5+ import sys
6+ try :
7+ import utime as time
8+ except ImportError :
9+ import time
10+ import _thread
11+
12+ # different implementations have different minimum sizes
13+ if sys .implementation == 'micropython' :
14+ sz = 2 * 1024
15+ else :
16+ sz = 32 * 1024
17+
18+ def foo ():
19+ pass
20+
21+ def thread_entry ():
22+ foo ()
23+
24+ # test set/get of stack size
25+ print (_thread .stack_size ())
26+ print (_thread .stack_size (sz ))
27+ print (_thread .stack_size () == sz )
28+ print (_thread .stack_size ())
29+
30+ # set stack size and spawn a few threads
31+ _thread .stack_size (sz )
32+ for i in range (2 ):
33+ _thread .start_new_thread (thread_entry , ())
34+
35+ time .sleep (0.2 )
36+ print ('done' )
Original file line number Diff line number Diff line change 1+ # test hitting the function recursion limit within a thread
2+ #
3+ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4+
5+ try :
6+ import utime as time
7+ except ImportError :
8+ import time
9+ import _thread
10+
11+ def foo ():
12+ foo ()
13+
14+ def thread_entry ():
15+ try :
16+ foo ()
17+ except RuntimeError :
18+ print ('RuntimeError' )
19+
20+ _thread .start_new_thread (thread_entry , ())
21+
22+ time .sleep (0.2 )
23+ print ('done' )
You can’t perform that action at this time.
0 commit comments