0

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()
0

1 Answer 1

2

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)
        [...]
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thanks. I'll have to read up more on nonlocal declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.