Question

I have three functions, functionA, functionB and functionC.
I want functionA and functionB to run simultaneously, and when a condition in functionB becomes true, I want functionA to stop, functionC to run, and then functionA to start running again, alongside functionB.

So basically, functionA would look something like:

def functionA:
    while True:
        if condition == true:
            functionB.stop()
            functionC()

Can anyone help me with this? Thanks

Was it helpful?

Solution

With parallel programming, there's always more than one way to do things. So someone else may have completely separate ideas on how to do this.

The way that comes to mind first is via Event. Keep three of them around, and toggle them on/off as necessary.

from threading import Thread, Event

def worker1(events):
    a,b,c = events
    while True:
        a.wait() # sleep here if 'a' event is set, otherwise continue

        # do work here

        if some_condition:
            c.clear() # put c to sleep
            b.set() # wake up, b    

def worker2(events):
    a,b,c = events
    while True:
        b.wait() 
        #do work
        if some_condition:
            a.clear()
            c.set()

def worker3(events):
    a,b,c = events
    while True:
        c.wait() 
        #do work
        if some_condition:
            b.clear()
            a.set()

And then start them up:

events = [Event() for _ in range(3)]
events[0].set()
events[1].set()
#events[2] starts un-set, i.e. worker3 sleeps at start

threads = []
threads.append(Thread(target=worker1, args=(events,)))
threads.append(Thread(target=worker2, args=(events,)))
threads.append(Thread(target=worker3, args=(events,)))

for t in threads:
    t.start()
for t in threads:
    t.join()

Rough untested code, and more verbose than it needs to be (you could write this all with one worker def that takes some additional arguments), but should hopefully set you on the right path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top