首页 > 解决方案 > 如何在类中运行线程函数?

问题描述

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

我正在尝试在类的方法中调用 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

我正在尝试做的事情可能吗?

标签: pythonmultithreadingpython-multithreading

解决方案


在 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)

推荐阅读