python - 如何解决我在 Python 中面临的多线程问题
问题描述
我有一种情况,我必须调用两种不同的方法来并行运行。我正在使用 Python 线程模块来实现这一点。但是,它们不是并行运行的两种方法,而是顺序运行。有人可以指导我了解我的代码有什么问题吗?
这适用于 Python 3.5,使用 threading 模块并有一个具有两种不同方法的类,必须并行运行。
## This is in template.py
from threading import Thread
import time
class createTemplate:
def __init__(self,PARAM1):
self.PARAM1=PARAM1
def method1(self):
print("Method1-START")
time.sleep(120)
print("Method1-END")
def method2(self):
print("Method2-START")
time.sleep(120)
print("Method2-END")
def final_method(self):
if self.PARAM1=="1":
m1=Thread(target=self.method1)
m1.run()
if self.PARAM1=="1":
m2=Thread(target=self.method2)
m2.run()
## This is in createTemplate.py
from template import createTemplate
template = createTemplate("1")
template.final_method()
实际输出:
方法 1-开始 方法 1-结束 方法 2-开始 方法 2-结束
预期输出:
方法1-开始方法2-开始方法1-结束方法2-结束
解决方案
而不是.run()
你应该打电话.start()
Thread.run()
将在当前线程的上下文中运行代码,但Thread.start()
实际上会产生一个新线程并在其上与现有线程并行运行代码。
尝试这个:
from threading import Thread
import time
class createTemplate:
def __init__(self,PARAM1):
self.PARAM1=PARAM1
def method1(self, arg):
print("Method1-START",arg)
time.sleep(5)
print("Method1-END",arg)
def method2(self,arg):
print("Method2-START",arg)
time.sleep(5)
print("Method2-END",arg)
def final_method(self):
if self.PARAM1=="1":
m1=Thread(target=self.method1, args=("A", )) # <- this is a tuple of size 1
m1.start()
if self.PARAM1=="1":
m2=Thread(target=self.method2, args=("B", )) # <- this is a tuple of size 1
m2.start()
推荐阅读
- linux - 在 CSV 中转换“表格数据”文件
- casting - FileNet Content Engine 查询比较定义为字符串的数字
- matlab - 对于matlab上具有3个变量的一阶和二阶普通非线性微分方程,我应该使用什么求解器?
- wordpress - (Wordpress)是否可以在我自己的插件中使用来自 3rd 方插件的短代码?
- c# - Visual Studio 2017 - 诊断工具 - 堆分析影响程序内存消耗
- postgresql - PostgreSQL 中最早和最早的时间
- excel - Excel 宏 - 将数据从一张表传输到另一张表时发送自动电子邮件(复制整行)
- python - 即使在通过 Selenium Python 升级到 v0.23 之后,Geckodriver 仍试图访问旧版本 v0.19
- javascript - 当我只想为一个输入字段显示错误气泡时,如何正确使用 reportValidity()?
- java - 使用 Prometheus 检测 Java 应用程序