以下是一種可能的解決方案。一個需要注意的是func需要比rate更快地返回,否則它不會像rate那樣頻繁地被調用,並且如果它的速度更快,它會比rate更快地被調度。這種方法看起來像很多工作,但再一次並行編程通常很困難。我希望再次看看代碼,以確保我沒有在某處等待的死鎖。
import multiprocessing, time, math
def func():
print('hello its now {}'.format(time.time()))
def wrapper(f, period, event):
last = time.time() - period
while True:
now = time.time()
# returns True if event is set, otherwise False after timeout
if event.wait(timeout=(last + period - now)):
break
else:
f()
last += period
def main():
period = 2
# event is the poison pill, setting it breaks the infinite loop in wrapper
event = multiprocessing.Event()
process = multiprocessing.Process(target=wrapper, args=(func, period, event))
process.start()
# burn some cpu cycles, takes about 20 seconds on my machine
x = 7
for i in range(50000000):
x = math.sqrt(x**2)
event.set()
process.join()
print('x is {} by the way'.format(x))
if __name__ == '__main__':
main()