【问题标题】:Python 3.6 Bitonic Sort with Multiprocessing library and multiple processes具有多处理库和多个进程的 Python 3.6 双调排序
【发布时间】:2018-04-23 02:32:24
【问题描述】:

我正在尝试使用 python multiprocessing 库和一个共享资源数组来实现 bitonic,该数组将在程序结束时进行排序。

我遇到的问题是,当我运行程序时,我收到一个提示,询问“您的程序仍在运行!您确定要取消它吗?”然后当我点击取消 N - 1 次(其中 N 是我尝试生成的进程数量)时,它就会挂起。

从命令行运行时,它只输出未排序的数组。当然,我希望它在程序结束时进行排序。

我一直在使用this resource 试图牢牢掌握如何减轻我的错误,但我没有任何运气,现在我在这里。

任何帮助将不胜感激,因为我真的没有其他地方可以求助。

我是使用 Python 3.6 编写的,这里是整个程序:

from multiprocessing import Process, Array
import sys
from random import randint

# remember to move this to separate file
def createInputFile(n):
    input_file = open("input.txt","w+")
    input_file.write(str(n)+ "\n")
    for i in range(n):
        input_file.write(str(randint(0, 1000000)) + "\n")

def main():
    # createInputFile(1024) # uncomment this to create 'input.txt'
    fp = open("input.txt","r") # remember to read from sys.argv
    length = int(fp.readline()) # guaranteed to be power of 2 by instructor
    arr = Array('i', range(length)) 
    nums = fp.read().split() 
    for i in range(len(nums)):
        arr[i]= int(nums[i]) # overwrite shared resource values
    num_processes = 8 # remember to read from sys.argv
    process_dict = dict() 
    change_in_bounds = len(arr)//num_processes
    low_b = 0 # lower bound 
    upp_b = change_in_bounds # upper bound 
    for i in range(num_processes): 
        print("Process num: " + str(i)) # are all processes being generated?
        process_dict[i] = Process(target=bitonic_sort, args=(True, arr[low_b:upp_b]) )
        process_dict[i].start()
        low_b += change_in_bounds
        upp_b += change_in_bounds

    for i in range(num_processes):
        process_arr[i].join()

    print(arr[:]) # Print our sorted array (hopefully)

def bitonic_sort(up, x):
    if len(x) <= 1:
        return x
    else: 
        first = bitonic_sort(True, x[:len(x) // 2])
        second = bitonic_sort(False, x[len(x) // 2:])
        return bitonic_merge(up, first + second)

def bitonic_merge(up, x): 
    # assume input x is bitonic, and sorted list is returned 
    if len(x) == 1:
        return x
    else:
        bitonic_compare(up, x)
        first = bitonic_merge(up, x[:len(x) // 2])
        second = bitonic_merge(up, x[len(x) // 2:])
        return first + second

def bitonic_compare(up, x):
    dist = len(x) // 2
    for i in range(dist):  
        if (x[i] > x[i + dist]) == up:
            x[i], x[i + dist] = x[i + dist], x[i] #swap



main()

【问题讨论】:

  • 我选择了Process 类而不是Pool 类,因为我觉得Process 类更易于交互。 Pool 是解决这类问题的正确方法吗?如果是这样,那么需要Process 的理想情况是什么?

标签: python-3.x sorting python-multiprocessing


【解决方案1】:

我不会深入探讨您代码中的所有语法错误,因为我确信您的 IDE 会告诉您这些。您遇到的问题是您缺少一个 if name==main。我将您的 def main() 更改为 def sort() 并写道:

if __name__ == '__main__':
    sort()

它成功了(在解决了所有语法错误之后)

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 2018-10-04
    • 2022-06-15
    • 2018-10-27
    • 2017-08-05
    • 1970-01-01
    • 2017-03-24
    • 2014-08-25
    • 1970-01-01
    相关资源
    最近更新 更多