AGawish
AGawish

Reputation: 98

Delay in a threaded function response

I am trying to replicate ES6 events behavior in python, so I wrote the following code:

from threading import Thread
from time import sleep

class Event:
    def __init__(self, action):
        self.action= action
        self.flag = False
        self.__watchFlag()
    def triggerAction(self):
        self.flag = True
    def __watchFlag(self):
        if self.flag:
            self.action()
            self.flag = False
        Thread(target=self.__watchFlag).start()


def action():
    print("Event triggered action.")
    
my_event = Event(action)

my_event.triggerAction()

Which works just fine except when I try to trigger the action two times consecutively, i.e:

my_event.triggerAction()
my_event.triggerAction()

Only 1 event is triggered, but if I add a sleep(1/10) in between each trigger, works well. So I am assuming there is a delay somewhere in the process, any ideas?

NOTE: PLS DON'T RECOMMEND ANY EVENTS LIBRARIES ALREADY EXISTING IN PYTHON, I KNOW THEM, THIS IS NOT MY END GOAL, THX.

Upvotes: 1

Views: 62

Answers (1)

dreamcrash
dreamcrash

Reputation: 51423

If you change your code to:

def triggerAction(self):
    print("setting to true")
    self.flag = True

when you have:

my_event.triggerAction()
my_event.triggerAction()

you get the following output:

setting to true
setting to true
Event triggered action.

But if you have :

my_event.triggerAction()
sleep(1/10)
my_event.triggerAction()

you got:

setting to true
Event triggered action.
setting to true
Event triggered action.

So in the first case you set flag to true immediately, so you don't given enough time for the context switch to kick in.

Upvotes: 1

Related Questions