3

我想在课堂上进行多处理。似乎只有 pathos.multiprocessing 能够帮助我。但是,当我实现它时,它无法加载我在 main 函数中使用的包。

from pathos.multiprocessing import ProcessingPool;
import time
import sys;
import datetime


class tester:
    def __init__(self):
        self.pool=ProcessingPool(2);

    def func(self,msg):
        print (str(datetime.datetime.now()));
        for i in xrange(1):
            print msg
            sys.stdout.flush();
        time.sleep(2)    

#----------------------------------------------------------------------
    def worker(self):
        """"""
        pool=self.pool
        for i in xrange(10):
               msg = "hello %d" %(i)
               pool.map(self.func,[i])
        pool.close()
        pool.join()
        time.sleep(40)



if __name__ == "__main__":
    print datetime.datetime.now();
    t=tester()
    t.worker()
    time.sleep(60);
    print "Sub-process(es) done."

错误是未定义全局名称“日期时间”。但它适用于主要功能!我的系统是Win7。

4

1 回答 1

4

我是 的作者pathos。如果您在非 Windows 系统上执行代码,它可以正常工作——即使是从解释器中。(它也适用于文件,也是如此)。

>>> from pathos.multiprocessing import ProcessingPool;
>>> import time
>>> import sys;
>>> import datetime
>>> class tester:
...     def __init__(self):
...         self.pool=ProcessingPool(2);
...     def func(self,msg):
...         print (str(datetime.datetime.now()));
...         for i in xrange(1):
...             print msg
...             sys.stdout.flush();
...         time.sleep(2)    
...     def worker(self):
...         """"""
...         pool=self.pool
...         for i in xrange(10):
...                msg = "hello %d" %(i)
...                pool.map(self.func,[i])
...         pool.close()
...         pool.join()
...         time.sleep(40)
... 
>>> datetime.datetime.now()
datetime.datetime(2015, 10, 21, 19, 24, 16, 131225)
>>> t = tester()
>>> t.worker()
2015-10-21 19:24:25.927781
0
2015-10-21 19:24:27.933611
1
2015-10-21 19:24:29.938630
2
2015-10-21 19:24:31.942376
3
2015-10-21 19:24:33.946052
4
2015-10-21 19:24:35.949965
5
2015-10-21 19:24:37.953877
6
2015-10-21 19:24:39.957770
7
2015-10-21 19:24:41.961704
8
2015-10-21 19:24:43.965193
9
>>>

问题是multiprocessing在 windows 上根本不同,因为 windows 没有真正的fork……,因此不像在具有fork. multiprocessing有一个分叉的pickler,它在幕后产生了一个subprocess……而非windows系统可以跨进程使用共享内存。

dill有一个check和一个在 some 上copy执行顺序的方法,其中使用共享内存,而使用(就像在 windows 中所做的那样)。这是mac上的方法,所以显然这不是问题。loads(dumps(object))objectcopychecksubprocessmultiprocessingcheck

>>> import dill
>>> dill.check(t.func)
<bound method tester.func of <__main__.tester instance at 0x1051c7998>>

您需要在 Windows 上做的另一件事是freeze_support在开头使用__main__(即 的第一行__main__)。在非 Windows 系统上是不必要的,但在 Windows 上却非常必要。这是文档。

>>> import pathos
>>> print pathos.multiprocessing.freeze_support.__doc__

    Check whether this is a fake forked process in a frozen executable.
    If so then run code specified by commandline and exit.

>>>
于 2015-10-21T18:41:32.770 回答