# Python使用多进程来并行运算 2021-08-21

2021/8/21 19:11:13 浏览：

# 汉诺塔

## 用递归的思路来模拟

n层的汉诺塔要从x杆移动到z杆，每一次只能移动一层，而且小的层只能放在大的层上面

## Python代码

``````import multiprocessing
``````

``````class myThread(multiprocessing.Process):
def __init__(self, n, x, y, z):
multiprocessing.Process.__init__(self)
self.n = n
self.x = x
self.y = y
self.z = z
``````

``````    def run(self):
start = time.time()
print("开始线程：", self.n)
hanoi(self.n, self.x, self.y, self.z)  #封装的汉诺塔函数
end = time.time()
time_run = end - start
print(f'结束线程：{self.n}，{self.n}层汉诺塔运行时间是{time_run}s')
``````

``````thread_1 = myThread(j, 'x', 'y', 'z')
``````

``````import multiprocessing
import sys
import time

def hanoi(n, x, y, z):
if n == 1:
# print(x,'——>',z)
pass
else:
hanoi(n - 1, x, z, y)
# print(x,'——>',z)
hanoi(n - 1, y, x, z)

def __init__(self, n, x, y, z):
multiprocessing.Process.__init__(self)
self.n = n
self.x = x
self.y = y
self.z = z

def run(self):
start = time.time()
print("开始线程：", self.n)
hanoi(self.n, self.x, self.y, self.z)
end = time.time()
time_run = end - start
print(f'结束线程：{self.n}，{self.n}层汉诺塔运行时间是{time_run}s')

sys.setrecursionlimit(10000)
if __name__ == '__main__':
for j in range(1, 50):