python多进程编程
def defin_canv(w, h):
canvas = np.zeros((h, w))
canvas[y0 - 1:y1, x0 - 1:x1] = 1
return canvas
result = []
pool = multiprocessing.Pool()
#将对象放入到类别中,包含了返回的对象
for anno in box:
result.append(pool.apply_async(defin_canv, args=(w, h)))
pool.close()
pool.join()
# 将数据取出来
for i in range(faces):
canvas[i] = result[i].get()
多进程不会修改参数列表中的内容,比如列表等,但可以返回值,这一点和多线程不一样。还有其他的一种(使用fork)来使用多进程的方法。去参考廖雪峰的博客吧!
多线程:
使用多线程时,从线程中取返回值不太好搞,我看好多人大致是使用新建一个类,继承Thread的方法,然后类中定义一个取值函数,使用对象的方法来调用取值。不过线程还可以将传入的数据直接修改,所以也可以使用参数列表中修改数据的方式。
canvas = np.zeros((n, h, w))
# multi thread
for i, anno in enumerate(box):
t = threading.Thread(target=defin_canv_Thre, args=(i, anno, canvas, w, h))
result.append(t)
for t in result:
t.setDaemon(True) # https://www.cnblogs.com/fnng/p/3670789.html
t.start()
result[-1].join()
t.setDaemon()是设置线程守护,否则线程将无限被挂起。
join()的作用是等子线程完成后,在去调用父线程,即回到调用多线程的程序中去。