Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

multithreading - the "block" of Queue.get(block=True, timeout=None) in python

I saw a piece of code as shown below, which achieves a manager driven by events. I was wondering what would be different if I changed the parameter timeout to be None in self.__event_queue.get(block=True, timeout=1) of the function run__.

from queue import Queue, Empty
from threading import *

class Event:
    def __init__(self, name=None):
        self.name= name
        self.dict= {}

class EventEngine:

    def __init__(self):
        self.__active = False
        self.__event_queue = Queue()
        self.__thread = Thread(target = self.run__)
        self.__handlers = {}

    def start_engine(self):
        self.__active = True
        self.__thread.start()

    def stop_engine(self):
        self.__active = False
        self.__thread.join()
    
    def run__(self):
        while self.__active == True:
            try:
                event = self.__event_queue.get(block=True, timeout=1) 
                self.process_event(event)
            except Empty:
                print('no event')
    
    def process_event(self, event):
        if event.name in self.__handlers:
            for handler in self.__handlers[event.name]:
                handler(event)
    
    def send_event(self, event):
        self.__event_queue.put(event)
    
    def add_event_listener(self,event_name,handler):
        try:
            handler_lst = self.__handlers[event_name]
        except KeyError:
            handler_lst = []
            self.__handlers[event_name] = handler_lst
        #if handler not in handler_lst:
        handler_lst.append(handler)
    
    def remove_event_listener(self,event_name,handler):
        try:
            handler_lst = self.handlers[event_name]
            if handler in handler_lst:
                handler_lst.remove(handler)
            if not handler_lst:
                del handler_lst[event_name]
        except KeyError:
            pass

Here is the test-code written by myself. I ran it after I changed the timeout to be None. I wrongly thought it would only print one time "post a new article / reading now, john / reading now, steve", however it actually printed two times:

from event_engine import *
class PublicAccount:
    def __init__(self, event_engine):
        self.__event_engine = event_engine
    
    def WriteNewArticle(self):
        event = Event(name='Article Write and Post')
        self.__event_engine.send_event(event)
        print('post a new article')


class Listener:
    def __init__(self, username):
        self.__username = username
    
    def ReadArticle(self, event):
        print('reading now,',self.__username)

def test():
    listern1 = Listener('john')
    listern2 = Listener('steve')

    eventManager = EventEngine()
    eventManager.add_event_listener('Article Write and Post', listern1.ReadArticle)
    eventManager.add_event_listener('Article Write and Post', listern2.ReadArticle)
    eventManager.start_engine()
    
    publicAcc = PublicAccount(eventManager)
    timer = Timer(0.5, publicAcc.WriteNewArticle)
    timer.start()
    timer = Timer(8, publicAcc.WriteNewArticle)
    timer.start()

if __name__== '__main__':
    test()
    print('test finished')

I believe "blocking" would block the function run__, but I am not quite sure it would block the instance so that other methods in this instance would not be executed (just like I wrongly thought the second call of send_event() in my test code would not be executed as the function run and the instance eventManager had been block at that time)

question from:https://stackoverflow.com/questions/65641076/the-block-of-queue-getblock-true-timeout-none-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...