文章目录
- 测试用的代码
- 错误
- 解决方法
测试用的代码
下面每一个对应一个jupyter notebook的单元格
import time
from multiprocessing import Process, Queue
def generator():c = 0while True:time.sleep(1.0) # read somethingyield cc += 1
%%timeds = generator()
for i in range(3):item = next(ds)time.sleep(1.0) # do somethingprint(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下运行这个单元格的话,会一直显示在运行,
%%timeds = 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_mainexitcode = _main(fd)File "D:\Anaconda\envs\AIE31\lib\multiprocessing\spawn.py", line 115, in _mainself = 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了。
%%timeds = 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