我一直在学习使用线程和时间,因为我想在我的脚本中发生一些事情,每个事情都在它自己的时间。
在具体示例中,我希望 FIR 每0.5秒从 TOT 中删除2,而 SEC 也会从 TOT < / strong>,但每2.1秒。我几乎整天都花在这个问题上,四处阅读并尝试不同的东西,但我被卡住了!
import time
import threading
suma = {
'fir': 2,
'sec': 3,
'tot': 80
}
def doCalc():
time.sleep(2.1)
suma['tot'] = suma['tot'] - suma['sec']
print 'second action: ' + str(suma['tot'])
while int(suma['tot']) > 0:
time.sleep(0.5)
print 'first action: ' + str(suma['tot'])
suma['tot'] = suma['tot'] - suma['fir']
for i in range(1):
threading.Thread(target=doCalc).start()
time.sleep(3)
print '_' * 10
答案 0 :(得分:0)
这是算法的一个版本。它启动两个线程,然后在几秒钟后发出信号退出。 (你不能终止Python线程,你必须礼貌地让他们退出。)所有对共享字典的写入都受到锁的保护。
感谢@Mark,@ dmitri和@dano。
TODO:传递args,正如@mark建议的那样。
import time
import threading
suma_lock = threading.Lock()
suma = {
'fir': 2,
'sec': 3,
'tot': 80
}
def doCalc():
time.sleep(2.1)
with suma_lock:
suma['tot'] -= suma['sec']
print 'second action: ' + str(suma['tot'])
def first():
while int(suma['tot']) > 0:
time.sleep(0.5)
print 'first action: ' + str(suma['tot'])
with suma_lock:
suma['tot'] -= suma['fir']
threading.Thread(target=first).start()
threading.Thread(target=doCalc).start()
time.sleep(3)
print '_' * 10
# hack: tell 'first' to exit
with suma_lock:
suma['tot'] = 0
for thread in threading.enumerate():
if thread != threading.current_thread():
thread.join()
print 'DONE'
first action: 80
first action: 78
first action: 76
first action: 74
second action: 69
first action: 69
__________
first action: 0
DONE