【问题标题】:Call function in 5 different thread and execute in parallel in Python 2.7在 5 个不同线程中调用函数并在 Python 2.7 中并行执行
【发布时间】:2015-11-28 11:05:00
【问题描述】:

这是我第一次在 python 中使用多线程。 我在 python 2.7.9 中找到了许多与多线程和多处理相关的文档,并且还研究了multi-threading link。但我不知道如何实现我的应用程序。我有基于 self.count 的应用程序,在下面的代码中是 5。我必须创建一个 5 个线程或进程,当我调用 d.sum(1,2) 这应该 在 5 中调用 sum 函数不同的线程并并行执行并使用线程名称和结果更新结果字典中的结果

现在我目前的方法正在连续发生。 但我想使用线程或进程将其设为并行。请帮助实现这一目标。

提前致谢。代码 sn-ps 非常感谢。

到目前为止我有代码。

class Base(object):

    def __init__(self): 
        self.count =5  # Count = 5 is used to create a 
                       #number of thread or process to run parallel

    def sum(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a + b

        return result

    def diff(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a - b

        return result

    def mull(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a * b

        return result

    def division(self, a, b):
        result = {}
        for i in range(0,self.count):
            result[i] = a / b
        return result

d = Base() 
print d.sum(1,2)
print d.diff(2,1)

【问题讨论】:

    标签: python multithreading multiprocessing


    【解决方案1】:

    由于 GIL,如果您使用线程,它们将不会并行运行。您需要使用多处理,以及多处理队列模块在进程之间进行通信。

    pymotw(本周 Python 模块)是获取此类模块信息的最佳位置之一。

    多处理部分的通信部分显示了一个完整的示例。

    https://pymotw.com/2/multiprocessing/communication.html

    【讨论】:

    • 非常感谢 Stuart Axon。您能否提供与我的申请相关的任何链接或文件。
    • @Sana,查看 StackOverflow 界面右侧的许多相关问题(和答案)。特别是,this one 在我身边突出显示。
    • 谢谢@Oliver W,您能否提供示例代码 sn-ps 或一些编码指南来构建我的应用程序
    • StuartAxon,您应该将指向该相关问题的链接添加到您的答案中(答案比 cmets 更永久,它将有助于引导未来的读者)
    • 是的,在平板电脑上输入了第一个答案,所以有点稀疏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2013-09-17
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多