Python 使用Queue()进行多处理:TypeError:can';t pickle\u thread.lock对象

Python 使用Queue()进行多处理:TypeError:can';t pickle\u thread.lock对象,python,multiprocessing,python-multiprocessing,Python,Multiprocessing,Python Multiprocessing,这是我的代码: def search(page, sort, start, end, q): print(mp.current_process()) results = req.request_buff_market_page(page, sort, start, end) for i in results: if(i[1] >= 20 and 'Souvenir' not in i[0]): q.put(i) if _

这是我的代码:

def search(page, sort, start, end, q):
    print(mp.current_process())
    results = req.request_buff_market_page(page, sort, start, end)

    for i in results:
        if(i[1] >= 20 and 'Souvenir' not in i[0]):
            q.put(i)


if __name__ == '__main__':
    page = 1
    q = queue.Queue()
    with mp.Pool(processes=mp.cpu_count()) as pool:
        print(page)
        pool.starmap(search, (page, 'asc', 200, 205, q))
        page += 1

    while not(q.empty()):
        print(q.get())
输出:

 Traceback (most recent call last):
      File "C:\Users\Andrew\Desktop\ultralight\mp_buff.py", line 33, in <module>
        pool.starmap(search, (page, 'asc', 200, 205, q))
    .........
    TypeError: can't pickle _thread.lock objects

您将多处理池视为多线程池,这是不同的。查看
multiprocessing.pool.ThreadPool

我将代码改为使用
workers.append(mp.Process(target=search,args=(page,'asc',200205,q))
而不是一个池,它起了作用。那么,您知道使用
多处理.pool.ThreadPool
还是
Process()
更好吗?更好的选择取决于您在辅助函数中执行的操作。如果您正在执行CPU限制的工作,但没有释放GIL,那么使用线程将不会提高性能;您必须使用子进程。@Andrew虽然直接将
队列
传递给
mp.Process
可能不会引发错误,但该队列在进程之间实际上不可用,因此您必须使用
mp.Queue
。您不能将
队列
多处理
一起使用。改用
多处理。队列
。@dano谢谢,我在发布这个问题后不久意识到了这一点。
 for i in range(mp.cpu_count()):
     workers.append(mp.Process(target=search, args=(page, 'asc', 200, 230, q_search)))
     page += 1
 for i in workers: i.start()
 for i in workers: i.join()