python - 如何在类中运行线程函数?
问题描述
我正在尝试在我的简单类中运行一个简单的线程函数。
我正在尝试在类的方法中调用 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
我正在尝试做的事情可能吗?
解决方案
在 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)
推荐阅读
- java - 序列化与实现
- python - matplotlib(anaconda)更新问题
- python - 如何根据列表的长度将包含列表的字典分成相等的部分
- r - 在R中的多元回归中找到样条回归的系数
- r - 如何将字符串匹配映射到具有缺失值的二维数据集中的变量
- react-native - 如何使用状态动态更改 React Native 转换?
- linux - 使用 bash 和 grep -c 对密码子进行排序和计数
- scala - 如何让 Hibernate 忽略某个名称的属性?
- android - Collections.sort 的比较函数在 Kotlin 中需要一个 Int 类型的值
- python - Visual Studio Code Python 加载自己的模块