python - 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:
- Initialisation of
result
to 0 and display of 0 on the UI delayed_sum(5, 10)
called. In 10 seconds, add 5 to result- Add 5 in 9 seconds
- Add 5 in 8 seconds
- Add 5 in 7 seconds
- Add 5 in 6 seconds
- Add 5 in 5 seconds
- Add 5 in 4 seconds
- Add 5 in 3 seconds and
delayed_sum(3, 5)
called. In 5 seconds, add 3 to result - Add 5 in 2 seconds and in 4 seconds add 3
- Add 5 in 1 second and in 3 seconds add 3
result += 5
and the UI displays 5 and in 2 seconds add 3- In 1 second add 3
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!
解决方案
推荐阅读
- angular - 如何使用 ngx-intl-tel-input 选择默认国家/地区
- python - JSON 模式生成器 Python
- c++ - 如何在不启用异常的情况下构建 boost 1.70.0?
- swift - ARKit – 如何显示来自放置在 SCNPlane 上的虚拟 SCNCamera 的提要?
- python-3.x - TomekLinks fit_sample(X,y) 花费大量时间
- laravel - 授权时访问 ForgotPasswordController
- java - 使用 Google 搜索引擎和 Java 搜索网络
- javascript - 如何在角度 6 中使用带有 forEach 的 case 语句?
- sql - 如何在没有数据库的情况下创建登录和用户注册
- android - Context.startForegroundService() 没有在 BroadcastReceiver 中调用 Service.startForeground()