在Python中使用多个线程计算阶乘 [英] Calculating factorial using multiple threads in Python

查看:79
本文介绍了在Python中使用多个线程计算阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python 2.7,我有一个任务来编写一个使用多个线程来计算阶乘的函数.我尝试使用传统的递归方法来做到这一点,例如

I use Python 2.7 and I have a task to write a function that calculates factorial using multiple threads. I tried to do that using traditional recursive approach, like

def factorial(n):
    if n < 1:
        return 1
    else:
        return n * factorial(n - 1)

但是,这种方式似乎不适合多线程.有什么方法可以使用多个线程来计算阶乘?

But it seems that this way doesn't suite for multithreading. Are there any ways to calculate factorial using multiple threads?

推荐答案

在多线程应用程序中,最好最小化不同线程之间存在的数据依赖性.

In multi-threading applications it is best to minimize the data dependencies that exists between the different threads.

在您提到的阶乘的递归解决方案中,很难找到不依赖于其他计算结果的计算.

In the recursive solution for factorials that you have mentioned it is hard to find calculations that do not depend on the results of other calculations.

一种独特的方法是将阶乘分解为多个部分.例如,对于两个线程,一个人可以做这样的事情:

A distinct approach would be to split the factorial in multiple parts. For example, for two threads one could do something like this:

n!= [1 * 2 * 3 * .. *(n/2)] * [(n/2 +1)* ... * n]

第一个线程将计算值:

v1 = 1 * 2 * 3 * .. *(n/2)

第二个线程将计算:

v2 =(n/2 + 1)* ... * n

然后,当两个线程都结束时,主线程将计算 n!= v1 * v2 .

And afterwards, when both threads are finished, the main thread would compute n! = v1 * v2.

通过将输入阶乘分解成 k 个不同的部分,而不是如上面的示例中的两个部分,可以将此方法推广到使用 k 个线程.

This can be generalized to use k threads by splitting the input factorial into k different parts instead of just two, as in the above example.

这篇关于在Python中使用多个线程计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆