阶乘程序冻结6位以上的数字

时间:2019-06-05 21:03:52

标签: python multiprocessing factorial

当我尝试计算6位数字的阶乘时,我的多进程程序冻结了,我不知道为什么。我可以看到它“重试”,但只能在“启动后”打印<=其中一个进程似乎不起作用...
对我来说,最大的问题是我可以运行5个数字,例如10000,但不能运行6个数字,例如100000。

from multiprocessing import Process, Queue
from os import cpu_count, system
from math import ceil
import platform


def factorial(numbers, que):
    opt = 1
    for i in numbers:
        opt *= i
    que.put(opt)


def ffactorial(numbers):
    opt = 1
    for i in numbers:
        opt *= i
    return opt


if __name__ == '__main__':
    clear_comm = ''
    if platform.system() == 'Linux' or platform.system() == 'Darwin':
        clear_comm = 'clear'
    if platform.system() == 'Windows':
        clear_comm = 'cls'

    system(clear_comm)
    while True:
        fact_inp = input('Enter number: ') # if 100000 program freezes
        # system(clear_comm)
        if fact_inp == 'q' or fact_inp == 'exit' or fact_inp == 'quit':
            exit()

        fact_num = int(fact_inp)

        cpuC = cpu_count()

        fact_num_arr = []
        for i in range(fact_num, 1, -1):
            fact_num_arr.append(i)

        arr_step = ceil(len(fact_num_arr) / cpuC)

        if arr_step > 1:
            fact_num_arr_s = []
            for i in range(cpuC):
                fact_num_arr_s.append(fact_num_arr[0:arr_step])
                del fact_num_arr[0:arr_step]

            processes = []
            opts = []
            print(cpuC)
            for i in range(cpuC):
                if len(fact_num_arr_s[i]) > 0:
                    q = Queue()
                    opts.append(q)
                    p = Process(target=factorial, args=(fact_num_arr_s[i], q))
                    processes.append(p)


            for i in processes:
                i.start()

            print('after start')
            for i in processes:
                print(i)

            for i in processes:
                i.join()

            realOpts = []
            print('after join')
            for i in opts:
                realOpts.append(i.get())

            for i in processes:
                i.terminate()

            print('working')
            fnfn = ffactorial(realOpts) # the last "stage"

        else: # if no need to add more processes 
            fnfn = ffactorial(fact_num_arr)

        print('DONE')
        print(f"{fact_num}! = {fnfn}")

计算机规格:    内存:32GB    cpu:英特尔酷睿i9    运行:Windows 10(64位)    python -v:3.7.3

0 个答案:

没有答案