首页 > 解决方案 > Delay function result while still being able to call the function and make result available

问题描述

I want my function delayed_sum(value, delay) to add the value to a global variable result with a certain delay in Python 3.x.

The idea is to connect my Python code with Electron to have a user interface. The user interface lets you view this global variable called result and let's you add some value to result with a certain delay expressed in seconds. I would like the variable result to be updated as soon as the delay has elapsed and while the function is running in the background, still be able to call the function.

If we have the time in seconds as follow:

  1. Initialisation of result to 0 and display of 0 on the UI
  2. delayed_sum(5, 10) called. In 10 seconds, add 5 to result
  3. Add 5 in 9 seconds
  4. Add 5 in 8 seconds
  5. Add 5 in 7 seconds
  6. Add 5 in 6 seconds
  7. Add 5 in 5 seconds
  8. Add 5 in 4 seconds
  9. Add 5 in 3 seconds and delayed_sum(3, 5) called. In 5 seconds, add 3 to result
  10. Add 5 in 2 seconds and in 4 seconds add 3
  11. Add 5 in 1 second and in 3 seconds add 3
  12. result += 5 and the UI displays 5 and in 2 seconds add 3
  13. In 1 second add 3
  14. result += 5 and the UI displays 8

I tried using time.sleep() but it freezes the control panel and I'm not able to call delayed_sum() while a first delayed_sum is being executed.

import time
import threading

result = 0

def delayed_sum(value, delay):
    t = threading.Thread(target=perform_sum, args=(value,delay,))
    t.start()
def perform_sum(value, delay):
    global result
    time.sleep(delay)
    result += value

When I use the code above, the action is indeed performed, but the result value isn't updated in the variable explorer before an other command line is executed.

I still haven't used Electron, but I'm afraid that if I ask my UI to read the value of result, what will be displayed won't be in real time. Could you guide me in making sure the UI will indeed read the correct value of result?

Many thanks!

标签: pythonpython-3.xdelaysleep

解决方案


推荐阅读