Python: what is the proper way to pass arguments to threading.Thread instance

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

I have extended threading.Thread - my idea is to do something like this:

class StateManager(threading.Thread):     def run(self, lock, state):         while True:             lock.acquire()             self.updateState(state)             lock.release()             time.sleep(60)

I need to be able to pass reference to my "state" object and eventually to a lock (I'm quite new to multi-threading and still confused about the necessity of locking in Python). What is the proper way to do it?

回答1:

pass them in the constructor, e.g.

class StateManager(threading.Thread):     def __init__(self, lock, state):         threading.Thread.__init__(self)         self.lock = lock         self.state = state                  def run(self):         lock = self.lock         state = self.state         while True:             lock.acquire()             self.updateState(state)             lock.release()             time.sleep(60)


回答2:

I'd say that it's easier to keep the threading part away from the StateManager object:

import threading import time  class StateManager(object):     def __init__(self, lock, state):         self.lock = lock         self.state = state      def run(self):         lock = self.lock         state = self.state         while True:             with lock:                 self.updateState(state)                 time.sleep(60)  lock = threading.Lock() state = {} manager = StateManager(lock, state) thread = threading.Thread(target=manager.run) thread.start()


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!