我有一个计算斐波那契数的函数。我正在尝试添加一个发送信号的功能,该信号指示我需要暂停该功能的运行。收到信号后,我将存储到目前为止计算出的所有数字。
当用户想要恢复该功能时,我可以加载文件并从停止的地方开始计算。
这是我的代码
<p>{{currentStatus}}</p>
<script>
import { eventBus } from "../../main";
export default {
data: function() {
return {
currentStatus: "Server Details are currently not updated"
};
},
create() {
eventBus.$on("statChanges", stat => {
this.currentStatus = stat;
});
}
};
</script>
该功能开始运行后,我无法确定的部分是如何使用此MAX = 100000
fibo_series = [0] * MAX
import pickle
def fib(start_value=0, stop_value=1000, stop_signal=False):
if not stop_signal:
for i in range(start_value, stop_value):
if i == 0:
fibo_series[i] = 0
elif i == 1 or i == 2:
fibo_series[i] = 1
else:
fibo_series[i] = fibo_series[i-1] + fibo_series[i-2]
return fibo_series[i]
else:
with open('fibo_series.pkl', 'wb') as f:
pickle.dump(fibo_series, f)
def reload_fib():
with open('fibo_series.pkl', 'rb') as f:
fibo_series = pickle.load(f)
start_value = fibo_series[1:].index(0) + 1
stop_value = len(fibo_series)
return fib(start_value, stop_value, stop_signal=False)
。函数启动后,值stop_signal
将被锁定。我知道要暂停功能的唯一方法是终止它,这不是我要执行的操作。
我该如何实现?
答案 0 :(得分:0)
我不确定停止和运行的条件是什么,但是一个简单的解决方法是为这两个函数使用全局变量。这并不比使用线程库锁更好,但是如果您的工作只是使用一个进程并且不需要复杂性,那么您可以尝试。
long_weekend weekday Date Public_Holiday? Weekend?
1 5 2015-01-10 no yes
0 0 2015-01-12 no no
0 1 2015-01-13 no no
0 2 2015-01-14 no no
0 3 2015-01-15 no no
0 4 2015-01-16 no no
1 5 2015-01-17 no yes
1 6 2015-01-18 no yes
0 0 2015-01-19 no no
0 1 2015-01-20 no no
0 2 2015-01-21 no no
0 3 2015-01-22 no no
1 4 2015-01-23 yes no
1 5 2015-01-24 no yes
1 6 2015-01-25 no yes
0 1 2015-01-27 no no
0 2 2015-01-28 no no
0 3 2015-01-29 no no
0 4 2015-01-30 no no
1 5 2015-01-31 no yes
0 0 2015-02-02 no no
0 1 2015-02-03 no no
0 2 2015-02-04 no no
0 3 2015-02-05 no no
0 4 2015-02-06 no no
1 5 2015-02-07 no yes
1 6 2015-02-08 no yes
1 0 2015-02-09 yes no
0 1 2015-02-10 no no
0 2 2015-02-11 no no
然后,每当用户想要停止执行时,都可以设置全局变量import threading
import time
MAX = 100000
fibo_series = [0] * MAX
import pickle
stop_signal = False
def fib(start_value=0, stop_value=1000):
for i in range(start_value, stop_value):
if (not stop_signal):
print('here', i)
time.sleep(1)
if i == 0:
fibo_series[i] = 0
elif i == 1 or i == 2:
fibo_series[i] = 1
else:
fibo_series[i] = fibo_series[i-1] + fibo_series[i-2]
else:
break
return fibo_series[i]
print('exiting... stop_signal: ', stop_signal)
with open('fibo_series.pkl', 'wb') as f:
pickle.dump(fibo_series, f)
def reload_fib():
with open('fibo_series.pkl', 'rb') as f:
fibo_series = pickle.load(f)
start_value = fibo_series[1:].index(0) + 1
stop_value = len(fibo_series)
global stop_signal
stop_signal = False
return fib(start_value, stop_value)
x = threading.Thread(target=fib )
x.start()
time.sleep(10)
stop_signal = True
print('finished...')
,输出为:
stop_signal=True
我希望这会有所帮助。