Reputation: 125
Suppose I want a program Foo.py
which has some arbitrary routines Bar()
, Quux()
, and Fizz()
. Let's say that the usual order of execution from a procedural perspective should be Bar() -> Quux() -> Fizz()
. However, Fizz()
should conditionally call a function Buzz()
depending on some runtime action, and calling Buzz()
at any time during Fizz()
should return the process back to Quux()
.
I have a fair understanding of how concurrent processes can be implemented in assembly using system calls depending on the architecture, but what options are available to me in Python, where I can't – and frankly would prefer not to – use lots of jumps and directly move an instruction pointer around? When searching for an answer, I found loops and recursion as a suggestion for going back in a program. I don't think a loop would work without stopping the Fizz()
process to wait for the condition check for Buzz()
, and I'm not sure how recursion could be implemented in this scenario either. (My Buzz()
would be like a "Back" button on a GUI).
Upvotes: 0
Views: 59
Reputation: 125
Using coroutines (multithreading) will provide the desired concurrent functionality. Source in the comments of the question and of user2357112's answer.
Upvotes: 0
Reputation: 77850
Perhaps flow like the below. Fizz
loops until some condition evokes a call to Buzz
. The same check that triggers the call breaks the loop.
import random
def Buzz():
print ("Buzz")
def Fizz():
print ("Fizz")
while True:
flip = random.random()
print (" ", flip)
if flip <= 0.5:
Buzz()
break
def Quux():
print ("Quux")
Fizz()
print ("Back in Quux")
def Bar():
print ("Bar")
Quux()
Bar()
Output:
Bar
Quux
Fizz
0.88313135192614
0.9782005471906149
0.6899740417799126
0.724911154764598
0.6193573809551899
0.3713918176393549
Buzz
Back in Quux
Upvotes: 0
Reputation: 281519
You don't need anything fancy here. The usual structured programming tools will work fine. Have Fizz
return after calling Buzz
, and have it return an indicator saying whether to go back to Quux
:
Bar()
while True:
Quux()
if not Fizz():
break
(If Buzz
's only effect is supposed to be returning execution to Quux
, don't have a Buzz
at all and just return.)
Upvotes: 1