python - 如何创建多个线程
问题描述
我正在研究python 3,我的课程如下。
class MyClass():
def values(self):
***values***
i =0
def check_values(self):
for i in ValueList[i:i+1]:
self.server_connect()
new_value = self.update.values(i)
def run(self):
self.check_values()
if __name__ == "__main__"
format1 = "%(asctime)s: %(message)s"
logging.basicConfig(format=format1, level=logging.INFO,
datefmt="%H:%M:%S")
for i in range(4):
thread = threading.Thread(target=MyClass().run())
threads.append(thread)
i += 1
print("the %s thread is running", thread)
thread.start()
没有创建线程,但代码有效。我无法在这里发现我做错了什么。
编辑
首先,我要感谢您的回复和时间。我必须根据团队的新更新更新代码并继承其他类,如下所示。
class MyClass(MainServer):
现在,服务器具有自己的运行功能,如下所示。
class MainServer(object):
***constructor***
***other functions ***
def run(self):
self.add_arguments()
self.parse_arguments()
self.check_values()
现在,没有 run(),我的代码无法正常运行。同时包括 run() 如下。
*** main ***
update_perform = MyClass()
for i range(4):
thread = threading.Thread(target=Myclass().run()) <-- code starts from here
threads.append(thread)
i += 1
print("the %s thread is running", thread)
thread.start() <-- not reaching till here
据我所知,我将需要 thread.start() 开始线程。所以我尝试了以下选项
class MyClass(MainServer):
***code as above***
def check_values(self):
self.server_authenticate()
update_value = self.update.values()
def run(self):
self.server_connect()
i = 0
threads = list()
for i in ValueList[i:i+1]:
print("Updating the value = ", i)
thread = threading.Thread(target=check_values(), args=[i])
thread.start()
i += 1
print("Currently running thread", thread)
threads.append(thread)
for thread in threads:
thread.join()
这里线程从开始执行,在打印中我可以看到如下
for threading :-
Currently running threads = <Thread(Thread-8, stopped 14852)>
但是对于我可以看到的值,只有一个正在处理中,如下所示
for value :-
Updating the value = 10 <- first value
因此,现在可能会创建线程,但不会并行执行值。
我无法弄清楚。
解决方案
像这样修改运行功能
def run(self):
self.check_values()
推荐阅读
- python - 迭代 h5 文件中的数据集,但不会保存更改
- c++ - 有没有办法从 Makefile 访问 VS Code c_cpp_properties.json 文件中的定义?
- python-3.x - 在写入百万行 csv 文件时计算 md5 - 无需将其读入内存
- php - php sql即使显示成功也不会删除行
- php - 显示每个用户的最新日志
- pine-script - 使用plotshape时如何使shapel自动显示?
- tensorflow - PyTorch 等效于 Tensorflow 线性层
- r - 如何制作高平滑、高分辨率的粒子运动动画
- debugging - Xcode 11.2.1 上的 com.apple.dt.SKAgent 消耗所有资源
- python - 如何从字符串python中删除所有表情符号(unicode)字符