Skip to content

Commit 2d5ea38

Browse files
committed
tests: Add 3 more tests for _thread module.
1 parent ed36632 commit 2d5ea38

File tree

3 files changed

+105
-0
lines changed

3 files changed

+105
-0
lines changed

tests/thread/thread_lock4.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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)

tests/thread/thread_stacksize1.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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')
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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')

0 commit comments

Comments
 (0)