简体   繁体   English

Python用多处理程序构建字典

[英]Python building a dictionary with multiprocessing

I am quite beginner with the multiprocessing module. 我是多处理模块的初学者。 In my code I am trying to build a dictionary with images from a given path. 在我的代码中,我试图用给定路径中的图像构建字典。 I wrote the following code: 我写了以下代码:

from multiprocessing import Pool
from PIL import Image, ImageTk
import glob

def process(path):
    print path
    im=ImageTk.PhotoImage(Image.open(path).resize((600, 600), Image.ANTIALIAS))
    name = (path.split('/')[1]).split('.')[0]
    return (name, im)

p = Pool(4)
input = glob.glob('./*.jpg')
image_list = dict(p.map(process, input))

If the code works correctly I would expect something like the following: 如果代码可以正常工作,我会期望如下所示:

{'-22': PIL.ImageTk.PhotoImage object at 0x7f6b66507150, {'-22':位于0x7f6b66507150的PIL.ImageTk.PhotoImage对象,

'-23': PIL.ImageTk.PhotoImage object at 0x7f6b66507190, ... and so on} '-23':位于0x7f6b66507190的PIL.ImageTk.PhotoImage对象,等等。}

... but instead I get the following error: ...但是我收到以下错误:

`multiprocessing.pool.MaybeEncodingError: Error sending result:`
`'[('-51', PIL.ImageTk.PhotoImage object at 0x7f6b664f6990),`
`('-47', PIL.ImageTk.PhotoImage object at 0x7f6b664f6fd0),`
`('-54', PIL.ImageTk.PhotoImage object at 0x7f6b66507050),`
`('-13', PIL.ImageTk.PhotoImage object at 0x7f6b665070d0),`
`('-45', PIL.ImageTk.PhotoImage object at 0x7f6b66507110),`
`('-49', PIL.ImageTk.PhotoImage object at 0x7f6b66507150),`
`('-48', PIL.ImageTk.PhotoImage object at 0x7f6b66507190),`
`('-26', PIL.ImageTk.PhotoImage object at 0x7f6b665071d0),`
`('-10', PIL.ImageTk.PhotoImage object at 0x7f6b66507210)]'.`
`Reason: 'UnpickleableError(tkapp object at 0x7f6b67c88e30,)'`

How can I solve this? 我该如何解决?

Multiprocessing is NOT threading. 多重处理不是线程化。 It is a completely separate process with its own interpreter. 它是一个完全独立的过程,带有自己的解释器。 This has some advantages- you can't accidentally created shared mutable state, which is great! 这有一些优点-您不能意外创建共享可变状态,这很棒! It has some disadvantages though- this is one of them. 尽管它有一些缺点-这是其中之一。

All data structures that are passed to or from a multiprocessing process have to be serialized/deserialized. 传入或传出多处理过程的所有数据结构都必须进行序列化/反序列化。 So the return value of that function, behind the scenes, has to be pickled- which as you can see, it cannot be. 因此,必须在后台隐藏该函数的返回值-正如您所看到的那样,实际上不能。

With your current design use Threading instead of Multiprocessing. 在您当前的设计中,请使用Threading而不是Multiprocessing。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM