我正在写一个python程序,我有三个例程需要在彼此之间切换,包括一个主循环,设置如下:
伪码:
main routine:
run routine,
while running:
if obtained signal A run routine A,
else if obtained signal B run routine B
routine A:
run routine,
while running:
if obtain signal B, run routine B,
else if completed with no signal run main
else if no signal, just keep running
routine B:
run routine,
while running
if obtain signal A, run routine A,
else if completed with no signal run main.
信号可以由处理程序发送,该处理程序设置一个具有关联锁定的变量。没有两个例程需要同时运行。
我正在考虑使用非抢先线程,并想知道是否存在一种方法来执行非抢占式线程python,其中线程可以专门屈服于另一个目标线程?我找到Yarn,但我不知道是否能解决问题。另外,我想知道是否有更好的方法来实现这一点,也许使用合作例程呢?
答案 0 :(得分:1)
那样的东西?
from random import choice
get_signal_somehow = lambda: choice(["A", "B"])
def main():
A = routine_a()
B = routine_b()
signal = get_signal_somehow()
while True:
if signal == 'A':
signal = next(A)
elif signal == 'B':
signal = next(B)
def routine_a():
#do stuff
if get_signal_somehow() == 'B':
yield 'B'
else:
yield 'A'
def routine_b():
#do stuff
if get_signal_somehow() == 'A':
yield 'A'
else:
yield 'B'