【问题标题】:How to fix the muti-threading issue which i am facing in Python如何解决我在 Python 中面临的多线程问题
【发布时间】:2020-07-07 22:26:34
【问题描述】:

我有一种情况,我必须调用两种不同的方法来并行运行。我正在使用 Python 线程模块来实现这一点。但是,它们不是并行运行的两种方法,而是顺序运行。有人可以指导我了解我的代码有什么问题吗?

这适用于 Python 3.5,使用线程模块并有一个具有两种不同方法的类,必须并行运行。

## 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-END 方法2-开始 方法2-END

预期输出:

方法1-开始 方法2-开始 方法1-END 方法2-END

【问题讨论】:

    标签: python python-3.x multithreading python-multithreading


    【解决方案1】:

    你应该打电话给.start()而不是.run()

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

    【讨论】:

    • 嗨@Adam.Er8,感谢您指出这一点。这符合我的预期。但是,如果我将一些输入参数传递给方法,它会再次按顺序运行。不允许传递参数吗?例如:- m1=Thread(target=self.method1("A")) m2=Thread(target=self.method2("B")) def method1(self,PARAM2): def method2(self,PARAM2):
    • target 应该始终是一个函数。您刚刚所做的是在创建线程时调用该函数,并将返回值作为目标传递。您需要使用 args 参数。我用示例代码编辑了我的答案
    猜你喜欢
    • 2020-07-25
    • 1970-01-01
    • 2022-12-22
    • 2021-12-26
    • 1970-01-01
    • 2020-08-14
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多