Skip to content

Commit dcc7c5b

Browse files
committed
tests/thread: Add tests for running GC within a thread, and heap stress.
1 parent c93d9ca commit dcc7c5b

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

tests/thread/thread_gc1.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# test that we can run the garbage collector within threads
2+
#
3+
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4+
5+
import gc
6+
import _thread
7+
8+
def thread_entry(n):
9+
# allocate a bytearray and fill it
10+
data = bytearray(i for i in range(256))
11+
12+
# do some work and call gc.collect() a few times
13+
for i in range(n):
14+
for i in range(len(data)):
15+
data[i] = data[i]
16+
gc.collect()
17+
18+
# print whether the data remains intact and indicate we are finished
19+
with lock:
20+
print(list(data) == list(range(256)))
21+
global n_finished
22+
n_finished += 1
23+
24+
lock = _thread.allocate_lock()
25+
n_thread = 4
26+
n_finished = 0
27+
28+
# spawn threads
29+
for i in range(n_thread):
30+
_thread.start_new_thread(thread_entry, (10,))
31+
32+
# busy wait for threads to finish
33+
while n_finished < n_thread:
34+
pass

tests/thread/thread_stress_heap.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# stress test for the heap by allocating lots of objects within threads
2+
# allocates about 5mb on the heap
3+
#
4+
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
5+
6+
import _thread
7+
8+
def last(l):
9+
return l[-1]
10+
11+
def thread_entry(n):
12+
# allocate a bytearray and fill it
13+
data = bytearray(i for i in range(256))
14+
15+
# run a loop which allocates a small list and uses it each iteration
16+
lst = 8 * [0]
17+
sum = 0
18+
for i in range(n):
19+
sum += last(lst)
20+
lst = [0, 0, 0, 0, 0, 0, 0, i + 1]
21+
22+
# check that the bytearray still has the right data
23+
for i, b in enumerate(data):
24+
assert i == b
25+
26+
# print the result of the loop and indicate we are finished
27+
with lock:
28+
print(sum, lst[-1])
29+
global n_finished
30+
n_finished += 1
31+
32+
lock = _thread.allocate_lock()
33+
n_thread = 10
34+
n_finished = 0
35+
36+
# spawn threads
37+
for i in range(n_thread):
38+
_thread.start_new_thread(thread_entry, (10000,))
39+
40+
# busy wait for threads to finish
41+
while n_finished < n_thread:
42+
pass

0 commit comments

Comments
 (0)