Bob*_*Bob 3 python multithreading multiprocessing
当使用 multiprocessing.JoinableQueue 生成进程的线程时,我收到 BrokenPipeError 。似乎是在程序完成工作并尝试退出之后发生的,因为它做了它应该做的所有事情。这是什么意思,有没有办法解决这个问题/安全忽略?
import requests
import multiprocessing
from multiprocessing import JoinableQueue
from queue import Queue
import threading
class ProcessClass(multiprocessing.Process):
def __init__(self, func, in_queue, out_queue):
super().__init__()
self.in_queue = in_queue
self.out_queue = out_queue
self.func = func
def run(self):
while True:
arg = self.in_queue.get()
self.func(arg, self.out_queue)
self.in_queue.task_done()
class ThreadClass(threading.Thread):
def __init__(self, func, in_queue, out_queue):
super().__init__()
self.in_queue = in_queue
self.out_queue = out_queue
self.func = func
def run(self):
while True:
arg = self.in_queue.get()
self.func(arg, self.out_queue)
self.in_queue.task_done()
def get_urls(host, out_queue):
r = requests.get(host)
out_queue.put(r.text)
print(r.status_code, host)
def get_title(text, out_queue):
print(text.strip('\r\n ')[:5])
if __name__ == '__main__':
def test():
q1 = JoinableQueue()
q2 = JoinableQueue()
for i in range(2):
t = ThreadClass(get_urls, q1, q2)
t.daemon = True
t.setDaemon(True)
t.start()
for i in range(2):
t = ProcessClass(get_title, q2, None)
t.daemon = True
t.start()
for host in ("http://ibm.com", "http://yahoo.com", "http://google.com", "http://amazon.com", "http://apple.com",):
q1.put(host)
q1.join()
q2.join()
test()
print('Finished')
Run Code Online (Sandbox Code Playgroud)
程序输出:
200 http://ibm.com
<!DOC
200 http://google.com
<!doc
200 http://yahoo.com
<!DOC
200 http://apple.com
<!DOC
200 http://amazon.com
<!DOC
Finished
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python\33\lib\multiprocessing\connection.py", line 313, in _recv_bytes
nread, err = ov.GetOverlappedResult(True)
BrokenPipeError: [WinError 109]
The pipe has been ended
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\33\lib\threading.py", line 901, in _bootstrap_inner
self.run()
File "D:\Progs\Uspat\uspat\spider\run\threads_test.py", line 31, in run
arg = self.in_queue.get()
File "C:\Python\33\lib\multiprocessing\queues.py", line 94, in get
res = self._recv()
File "C:\Python\33\lib\multiprocessing\connection.py", line 251, in recv
buf = self._recv_bytes()
File "C:\Python\33\lib\multiprocessing\connection.py", line 322, in _recv_bytes
raise EOFError
EOFError
....
Run Code Online (Sandbox Code Playgroud)
(为其他线程消除相同的错误。)
如果我将 JoinableQueue 切换为多线程部分的queue.Queue,一切都会修复,但为什么呢?
multiprocessing.Queue.get发生这种情况是因为当主线程退出时,您让后台线程在调用中阻塞,但它仅在某些条件下发生:
multiprocessing.Queue.get当主线程退出时,守护线程正在运行并阻塞。multiprocessing.Process正在运行。multiprocessing不是'fork'.Connection例外情况是告诉您,当呼叫multiprocessing.JoinableQueue内部get()发送了时,正在侦听的另一端EOF。一般来说,这意味着另一侧已Connection关闭。在关闭期间发生这种情况是有道理的——Python 在退出解释器之前清理所有对象,其中清理的一部分涉及关闭所有打开的Connection对象。我还无法弄清楚为什么只有(并且总是)在 amultiprocessing.Process已生成(不是分叉,这就是为什么默认情况下在 Linux 上不会发生)并且仍在运行时才会发生这种情况。如果我创建一个multiprocessing.Process只是在while循环中休眠的东西,我什至可以重现它。Queue它根本不需要任何物体。无论出于何种原因,正在运行的、生成的子进程的存在似乎保证会引发异常。它可能只是导致事物被破坏的顺序正好适合竞争条件的发生,但这只是一个猜测。
无论如何,使用 aqueue.Queue代替multiprocessing.JoinableQueue是修复它的好方法,因为您实际上并不需要 a multiprocessing.Queue。您还可以通过将哨兵发送到其队列来确保后台线程和/或后台进程在主线程之前关闭。因此,让这两种run方法都检查哨兵:
def run(self):
for arg in iter(self.in_queue.get, None): # None is the sentinel
self.func(arg, self.out_queue)
self.in_queue.task_done()
self.in_queue.task_done()
Run Code Online (Sandbox Code Playgroud)
完成后发送哨兵:
threads = []
for i in range(2):
t = ThreadClass(get_urls, q1, q2)
t.daemon = True
t.setDaemon(True)
t.start()
threads.append(t)
p = multiprocessing.Process(target=blah)
p.daemon = True
p.start()
procs = []
for i in range(2):
t = ProcessClass(get_title, q2, None)
t.daemon = True
t.start()
procs.append(t)
for host in ("http://ibm.com", "http://yahoo.com", "http://google.com", "http://amazon.com", "http://apple.com",):
q1.put(host)
q1.join()
# All items have been consumed from input queue, lets start shutting down.
for t in procs:
q2.put(None)
t.join()
for t in threads:
q1.put(None)
t.join()
q2.join()
Run Code Online (Sandbox Code Playgroud)