Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7e7912f

Browse files
committed
Protect all uses of the random generator with a lock.
Particles break out of their loop when the main loop exits.
1 parent 3d3a52a commit 7e7912f

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

Demo/tkinter/guido/brownian.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# An example of a multi-threaded Tkinter program.
1+
# Brownian motion -- an example of a multi-threaded Tkinter program.
22

33
from Tkinter import *
44
import random
@@ -14,22 +14,35 @@
1414
LAMBDA = 10
1515
FILL = 'red'
1616

17+
stop = 0 # Set when main loop exits
18+
19+
lock = threading.Lock() # Protects the random generator
20+
1721
def particle(canvas):
1822
r = RADIUS
19-
x = random.gauss(WIDTH/2.0, SIGMA)
20-
y = random.gauss(HEIGHT/2.0, SIGMA)
23+
lock.acquire()
24+
try:
25+
x = random.gauss(WIDTH/2.0, SIGMA)
26+
y = random.gauss(HEIGHT/2.0, SIGMA)
27+
finally:
28+
lock.release()
2129
p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL)
22-
while 1:
23-
dx = random.gauss(0, BUZZ)
24-
dy = random.gauss(0, BUZZ)
30+
while not stop:
31+
lock.acquire()
32+
try:
33+
dx = random.gauss(0, BUZZ)
34+
dy = random.gauss(0, BUZZ)
35+
dt = random.expovariate(LAMBDA)
36+
finally:
37+
lock.release()
2538
try:
2639
canvas.move(p, dx, dy)
2740
except TclError:
2841
break
29-
dt = random.expovariate(LAMBDA)
3042
time.sleep(dt)
3143

3244
def main():
45+
global stop
3346
root = Tk()
3447
canvas = Canvas(root, width=WIDTH, height=HEIGHT)
3548
canvas.pack(fill='both', expand=1)
@@ -39,6 +52,9 @@ def main():
3952
for i in range(np):
4053
t = threading.Thread(target=particle, args=(canvas,))
4154
t.start()
42-
root.mainloop()
55+
try:
56+
root.mainloop()
57+
finally:
58+
stop = 1
4359

4460
main()

0 commit comments

Comments
 (0)