如何在一个类中运行线程函数?

时间:2019-07-19 22:00:00

标签: python multithreading python-multithreading

我正在尝试在我的简单类中运行一个简单的线程函数。

我试图在类的方法中调用Thread函数。此方法中的Thread函数指向类中的另一个方法。我测试的方法是通过python终端。这是我在increment_thread.py中的课程:

from threading import Thread
import time

class Increment:
    def __init__(self):
        self.count = 0

    def add_one(self):
        while True:
            self.count = self.count + 1
            time.sleep(5)

    def start(self):
        background_thread = Thread(target=add_one)
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

为了测试这一点,我在终端中运行python,这将提示python终端。

然后,我运行以下几行:

from increment_thread import Increment
inc = Increment()
inc.get_count() # Yields 0
inc.start()

我希望线程启动并指示“已开始计数”,但出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/python-sandbox/increment_thread.py", line 14, in start
    background_thread = Thread(target=add_one)
NameError: name 'add_one' is not defined

我想做的是可能的吗?

2 个答案:

答案 0 :(得分:3)

在Thread构造函数中,它应该不是target = self.add_one而不是target = add_one

传递参数:

from threading import Thread
import time

class Increment:

    count = None

    def __init__(self):
        self.count = 0

    def add_one(self, start_at=0):
      self.count = start_at
      while True:    
        self.count = self.count + 1
        time.sleep(5)

    def start_inc(self, start_at=count):
        # Pass args parameter as a tuple
        background_thread = Thread(target=self.add_one, args=(start_at,))
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

if __name__ == "__main__":

  inc = Increment()
  inc.get_count() # Yields 0
  inc.start_inc(start_at=5)
  while True:
    inc.get_count()
    time.sleep(2)

答案 1 :(得分:2)

就像类字段一样,需要使用self.method语法来引用类方法。所以

    def start(self):
        background_thread = Thread(target=self.add_one)
        background_thread.start()
        print("Started counting up")
        return