Python:将参数传递给threading.Thread实例的正确方法是什么 [英] Python: what is the proper way to pass arguments to threading.Thread instance

查看:2030
本文介绍了Python:将参数传递给threading.Thread实例的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经扩展了threading.Thread-我的想法是做这样的事情:

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)

我需要能够传递对状态"对象的引用,并最终传递给锁(我对多线程非常陌生,并且对在Python中锁定的必要性仍然感到困惑).正确的方法是什么?

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?

推荐答案

在构造函数中传递它们,例如

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)

这篇关于Python:将参数传递给threading.Thread实例的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆