kquick / Thespian

Python Actor concurrency library
MIT License
189 stars 24 forks source link

I want to do infinite loop (for some continuous process) inside an Thespian actor. #68

Closed andreikee closed 3 years ago

andreikee commented 3 years ago

I tried to start the loop in the receiveMessage_Run() method (see code below), but I cannot to end the loop. The actor is blocked to receive new messages.

Can somebody help me with this task? How can I run infinite loop (it seems, asynchronous) and save possibility to react to other messages and possibility to stop the loop and actor?

My testing code:

from thespian.actors import ActorExitRequest, ActorSystem, Actor, ActorTypeDispatcher
import time
import random

# Message 'Run'
class Run():
    pass

# Message 'Stop'
class Stop():
    pass

class Actor(ActorTypeDispatcher):
    def __init__(self):
        self.stop = False

    # It seems, it must be asynchronous
    def loop(self):
        while not self.stop:
            time.sleep(1)
            print(random.random())

    def receiveMsg_Run(self, data, sender):
        self.loop()
        self.send(sender, 'Finished the loop.')

    def receiveMsg_Stop(self, msg, sender):
        self.stop = True
        self.send(self.myAddress, ActorExitRequest)
        print('*' * 1000)

    def receiveMsg_ActorExitRequest(self, msg, sender):
        self.stop = True
        time.sleep(1)

if __name__ == '__main__':
    asys = ActorSystem('multiprocQueueBase')

    loop = asys.createActor(Actor)

    resp = asys.ask(loop, Run())
    print(resp)
    time.sleep(4)
    asys.tell(loop, Stop())

    ActorSystem().shutdown()
kquick commented 3 years ago

Answered at https://stackoverflow.com/questions/64537024/infinite-asynchronous-loop-in-the-thespian-actors/64576499#64576499, just adding the link here for future reference.