测试用的代码
下面每一个对应一个jupyter notebook的单元格
import time
from multiprocessing import Process, Queue
def generator():
c = 0
while True:
time.sleep(1.0)
yield c
c += 1
%%time
ds = generator()
for i in range(3):
item = next(ds)
time.sleep(1.0)
print(item)
0
1
2
CPU times: user 3.27 ms, sys: 456 μs, total: 3.73 ms
Wall time: 6.01 s
def kernel(func, q: Queue):
ds = func()
while True:
item = next(ds)
q.put(item)
def multi_generator(func):
q = Queue()
p = Process(target=kernel, args=(func, q))
p.start()
while True:
item = q.get()
yield item
在windows下运行这个单元格的话,会一直显示在运行,
%%time
ds = multi_generator(generator)
for i in range(3):
item = next(ds)
time.sleep(1.0)
print(item)
错误
运行上面的代码,后台会报如下错
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "D:\Anaconda\envs\AIE31\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "D:\Anaconda\envs\AIE31\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'kernel' on <module '__main__' (built-in)>
解决方法
1、些处解决方案,是利用Windows 10 下的WSL的Linux系统解决的。 怎样配置WSL,请参考链接https://blog.csdn.net/jasneik/article/details/123782018 直接打开Ubuntu 控制台,运行jupyter notebook,一般不会像Windows下的会自动跳转,可以把jupyter notebook含token的链接拷贝到浏览器打开。类似如下的链接 然后把上面的代码拷,再运行,就OK了。
%%time
ds = multi_generator(generator)
for i in range(3):
item = next(ds)
time.sleep(1.0)
print(item)
0
1
2
CPU times: user 9.26 ms, sys: 1.38 ms, total: 10.6 ms
Wall time: 4.06 s
2、可以参考此方面,是把方法写到临时文件(我没有试过) https://blog.csdn.net/e274794140/article/details/87286190
|