Python多进程不能将信息放入队列

1.Python多进程不能将信息放入队列
2.代码:

from urllib import request
from bs4 import BeautifulSoup
from multiprocessing import Manager
from multiprocessing import Pool
import os

def hand_url(url,name,queue):
    room_message = {} #存放我需要的信息

    print(name,os.getpid())
    one_roomlist=[]
    req=request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36')
    with request.urlopen(req)as f:
        data = f.read().decode()
    soup = BeautifulSoup(data, 'html.parser')
    clear_1 = soup.find_all(class_="table_type_7 responsive_table full_width t_align_l")
    clear_1 = clear_1[0].tbody.contents
    for i in clear_1:
        if i != '\n':
            message_small = []
            for x in i.strings:
                if x != '\n':
                    message_small.append(x)


            one_roomlist.append(message_small)

        room_message[name] = one_roomlist

                  #前半部分为爬去网页信息和筛选内容
    print(room_message)
    queue.put(room_message)     #程序在这里卡住了,room_message为一个字典
    print('ok')



if __name__ == '__main__':
    queue=Manager().Queue()
    pool = Pool(4)
    pool.apply_async(hand_url,('http://202.115.129.139:81/trainingroomnote?roomid=91','A405',queue))
    pool.close()
    pool.join()
    print(queue.get())

3.问题截图

clipboard.png

4.我自己尝试把print(room_message)得到的内容直接复制添加到队列里面是可以的,但是一旦改成queue.put(room_message)程序是卡在这里的

阅读 2.2k
1 个回答

道友 你首先要明白问题所在,到底是什么原因。
打个断点,进去到queue队列里的代码看看。看看queue里面的代码是卡在了哪一步,报错了吗?如果报错了,是什么错误。
有时候,代码会捕获异常,让你无法直接判断错误所在。

回到这个问题,程序卡住了,是不是队列满了?是不是有异常未捕获? 是不是达到了竞态条件?是不是发生了死锁?(是的是的 就是你)

这个根本原因在于 你的队列queue其实是共享变量,多线程不安全。线程池里对该队列的操作达到了竞态条件,所以一直等待对象锁的释放(同步阻塞ing)
把程序好好改一下吧,做个同步,给队列加个锁就行了。
好好看一下多线程的内存模型,消费者生产者模式 就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进