Python (2.7), time.sleep, 循环, 线程

0 投票
1 回答
2338 浏览
提问于 2025-04-18 09:26

我最近在学习如何使用线程和时间,因为我想让我的脚本里有几个事情可以同时进行,各自按照自己的时间运行。

具体来说,我希望FIR每隔0.5秒从TOT中减去2,而SEC则每隔2.1秒也从TOT中减去一些东西。我花了几乎一整天在这个问题上,查资料和尝试不同的方法,但我现在卡住了!

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

1 个回答

0

这是这个算法的一个版本。它启动了两个线程,然后在几秒钟后通知它们退出。(你不能直接终止Python线程,你必须礼貌地请求它们退出。)所有对共享字典的写入操作都受到锁的保护。

感谢@Mark、@dmitri和@dano。

待办事项:按照@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

撰写回答