1# test concurrent mutating access to a shared list object
2#
3# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4
5import _thread
6
7# the shared list
8li = list()
9
10# main thread function
11def th(n, lo, hi):
12    for repeat in range(n):
13        for i in range(lo, hi):
14            li.append(i)
15            assert li.count(i) == repeat + 1
16
17            li.extend([i, i])
18            assert li.count(i) == repeat + 3
19
20            li.remove(i)
21            assert li.count(i) == repeat + 2
22
23            li.remove(i)
24            assert li.count(i) == repeat + 1
25
26    with lock:
27        global n_finished
28        n_finished += 1
29
30
31lock = _thread.allocate_lock()
32n_thread = 4
33n_finished = 0
34
35# spawn threads
36for i in range(n_thread):
37    _thread.start_new_thread(th, (4, i * 60, (i + 1) * 60))
38
39# busy wait for threads to finish
40while n_finished < n_thread:
41    pass
42
43# check list has correct contents
44li.sort()
45print(li)
46