Ethan
Ethan

Reputation: 37

How can I modify variables across different threads in Python?

I can't seem to change the x or y values in the code below. I thought the second thread will wait until the the calculation is complete?

I don't know what fundamentally I'm doing wrong here?

from threading import Event, Thread
import numpy as np

def test():
    x = [0, 1]
    y = [1, 3]

    def calc_callback(ev):
        x = np.linspace(-5, 5, 100)
        y = np.sin(x)/x
        ev.set()


    def display_callback(ev):
        ev.wait()
        print(x)
        print(y)

    completion_event = Event()
    Thread(target=calc_callback, args=[completion_event]).start()
    Thread(target=display_callback, args=[completion_event]).start()


if __name__ == '__main__':
    test()

Upvotes: 0

Views: 224

Answers (1)

Michael Butscher
Michael Butscher

Reputation: 10959

Using x = assignment in calc_callback creates a new variable x independent of the x in enclosing test(). Only this new variable is modified and then thrown away (same for y).

Try nonlocal declaration (needs Python 3.x):

[...]

    def calc_callback(ev):
        nonlocal x, y
        x = np.linspace(-5, 5, 100)
        [...]

Upvotes: 2

Related Questions