为什么在类里运行多进程就报错?
为什么在类里运行多进程就报错?点’执行‘按键报错,点’正常‘就没有报错,请问多进程应该怎么修改才可以在类中正常运行,谢谢!!!
import multiprocessing as mp
import tkinter as tk
class Test:
def __init__(self):
def job(q):
res = 0
for i in range(1000000):
res += i + i**2 + i**3
q.put(res) # queue
def doit():
q1 = mp.Queue()
q2 = mp.Queue()
p1 = mp.Process(target=job, args=(q1,))
p2 = mp.Process(target=job, args=(q2,))
p1.start()
p2.start()
p1.join()
p2.join()
res1 = q1.get()
res2 = q2.get()
print('multicore:',res1 + res2)
def nomal():
res = 0
for a in range(2):
for i in range(1000000):
res += i + i**2 + i**3
print('nomal:',res)
root = tk.Tk()
frame = tk.Frame(root,height=400,width=400)
frame.grid(row=0)
theButton = tk.Button(frame,height=4,width=10,text='正常',command=nomal)
theButton.grid(row=0,column=0)
theButton1 = tk.Button(frame,height=4,width=10,text='执行',command=doit)
theButton1.grid(row=1,column=0)
root.mainloop()
if __name__ == '__main__':
go = Test()
import multiprocessing as mp
import tkinter as tk
class Test():
def newtk(self):
root = tk.Tk()
frame = tk.Frame(root,height=400,width=400)
frame.grid(row=0)
theButton1 = tk.Button(frame,height=4,width=10,text='执行',command=self.doit)
theButton1.grid(row=1,column=0)
root.mainloop()
def job(self,q):
res = 0
for i in range(1000000):
res += i + i**2 + i**3
q.put(res) # queue
def doit(self):
q = mp.Queue()
p1 = mp.Process(target=self.job, args=(q,))
p2 = mp.Process(target=self.job, args=(q,))
p1.start()
p2.start()
p1.join()
p2.join()
res1 = q.get()
res2 = q.get()
print('multicore:',res1 + res2)
if __name__ == '__main__':
go = Test()
go.newtk()
代码问题不大 缩进有问题 __init__ 函数和其他函数应该是并列关系。
【Spyder python3.6 测试通过】
import multiprocessing as mp
import tkinter as tk
class Test():
def __init__(self):
root = tk.Tk()
frame = tk.Frame(root,height=400,width=400)
frame.grid(row=0)
theButton1 = tk.Button(frame,height=4,width=10,text='执行',command=self.doit)
theButton1.grid(row=1,column=0)
root.mainloop()
def job(self,q):
res = 0
for i in range(1000000):
res += i + i**2 + i**3
q.put(res) # queue
def doit(self):
q = mp.Queue()
p1 = mp.Process(target=self.job, args=(q,))
p2 = mp.Process(target=self.job, args=(q,))
p1.start()
p2.start()
p1.join()
p2.join()
res1 = q.get()
res2 = q.get()
print('multicore:',res1 + res2)
if __name__ == '__main__':
go = Test()
楼主我最近也在学多线程 一起交流啊 想结合UI 用多线程防止界面未响应 或者卡顿{:10_254:} 591821661 发表于 2021-3-26 19:18
楼主我最近也在学多线程 一起交流啊 想结合UI 用多线程防止界面未响应 或者卡顿
我是用到才学的,完成代码就不再学了, 逃兵 发表于 2021-3-26 11:37
如果方便的话,麻烦帮我看一下另一个问题,谢谢
页:
[1]