Skip to content

Commit b7274e9

Browse files
committed
tests/thread: Add test for concurrent mutating of user instance.
1 parent 2e4cdae commit b7274e9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

tests/thread/mutate_instance.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# test concurrent mutating access to a shared user instance
2+
#
3+
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
4+
5+
import _thread
6+
7+
# the shared user class and instance
8+
class User:
9+
def __init__(self):
10+
self.a = 'A'
11+
self.b = 'B'
12+
self.c = 'C'
13+
user = User()
14+
15+
# main thread function
16+
def th(n, lo, hi):
17+
for repeat in range(n):
18+
for i in range(lo, hi):
19+
setattr(user, 'attr_%u' % i, repeat + i)
20+
assert getattr(user, 'attr_%u' % i) == repeat + i
21+
22+
with lock:
23+
global n_finished
24+
n_finished += 1
25+
26+
lock = _thread.allocate_lock()
27+
n_repeat = 30
28+
n_range = 300
29+
n_thread = 4
30+
n_finished = 0
31+
32+
# spawn threads
33+
for i in range(n_thread):
34+
_thread.start_new_thread(th, (n_repeat, i * n_range, (i + 1) * n_range))
35+
36+
# busy wait for threads to finish
37+
while n_finished < n_thread:
38+
pass
39+
40+
# check user instance has correct contents
41+
print(user.a, user.b, user.c)
42+
for i in range(n_thread * n_range):
43+
assert getattr(user, 'attr_%u' % i) == n_repeat - 1 + i

0 commit comments

Comments
 (0)