首页 > 解决方案 > 如何解决我在 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-结束

标签: pythonpython-3.xmultithreadingpython-multithreading

解决方案


而不是.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()

推荐阅读