Python switching between routines
Question: 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:

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. 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? I found
[Yarn](http://sifter.org/~simon/yarn/about.html), but I don't know if that
solves the problem. In addition, I was wondering if there is better way to
accomplish this, maybe using co-routines instead?


Answer: 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'
    

