简体   繁体   English

Python在例程之间切换

[英]Python switching between routines

I am writing a python program where I have three routines that need to switch between each other including a main loop, set up as follows: 我正在编写一个python程序,其中有三个例程需要相互切换,包括一个主循环,设置如下:

pseudo-code: 伪代码:

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.

Where signal could sent by a handler that sets a variable that has an associated Lock on it. 处理程序可以在哪里发送信号,该处理程序会设置一个具有关联的Lock的变量。 No two routines need to run simultaneously. 无需两个例程同时运行。

I was thinking of using non-preemptive threads, and wondering if there exists a way to do non-preemptive threading python where threads can specifically yield to another target thread? 我当时正在考虑使用非抢占式线程,并且想知道是否存在一种方法来进行非抢占式线程化python,其中线程可以专门屈服于另一个目标线程? I found Yarn , but I don't know if that solves the problem. 我找到了Yarn ,但是我不知道这是否可以解决问题。 In addition, I was wondering if there is better way to accomplish this, maybe using co-routines instead? 另外,我想知道是否有更好的方法来完成此操作,也许改用协同例程?

Something like that? 这样的事吗?

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM