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
6try:
7    import utime as time
8except ImportError:
9    import time
10import _thread
11
12
13def last(l):
14    return l[-1]
15
16
17def thread_entry(n):
18    # allocate a bytearray and fill it
19    data = bytearray(i for i in range(256))
20
21    # run a loop which allocates a small list and uses it each iteration
22    lst = 8 * [0]
23    sum = 0
24    for i in range(n):
25        sum += last(lst)
26        lst = [0, 0, 0, 0, 0, 0, 0, i + 1]
27
28    # check that the bytearray still has the right data
29    for i, b in enumerate(data):
30        assert i == b
31
32    # print the result of the loop and indicate we are finished
33    with lock:
34        print(sum, lst[-1])
35        global n_finished
36        n_finished += 1
37
38
39lock = _thread.allocate_lock()
40n_thread = 10
41n_finished = 0
42
43# spawn threads
44for i in range(n_thread):
45    _thread.start_new_thread(thread_entry, (10000,))
46
47# wait for threads to finish
48while n_finished < n_thread:
49    time.sleep(1)
50