Предупреждение о доступе к памяти для multiprocessing.pool.ThreadPool, или может быть исправлено с помощью переменных аргументов? - PullRequest
0 голосов
/ 17 марта 2020

У меня есть следующий код, который хорошо работает:

from multiprocessing.pool import ThreadPool
from multiprocessing import Pool
import requests


# Retrieve data using get request
def get_docs():
    try:
        docs = requests.get(url).json()['data']
        return docs
    except ValueError:
        print("ValueError")

# Index dictionary for each attribute
def get_attributes(doc):
    x1, x2, x3, x4 = doc["id"], doc["created_utc"], doc["title"], doc["subreddit"]
    return (x1, x2, x3, x4)

# Map each document to the attribute function
def get_data(docs):
    with ThreadPool(4) as pool:
        results = pool.map(get_attributes, docs)
        return results


docs = get_docs()
data = get_data(docs)

print(data)

Но я действительно хочу, чтобы get_attributes () выглядела так:

def get_attributes(doc):
    """
    Using either Pool or ThreadPool
    """
    with Pool(4) as p:
        results = p.map(some_function(doc), ["id", "created_utc", "title", "subreddit"])
        return results


# Where the get_attributes function iteratively maps attributes to one document:
def some_function(doc, arg):
    return doc[arg]


# And then ultimately this should work
def get_data(docs):
    with ThreadPool(4) as pool:
        results = pool.map(get_attributes, docs)
        return results

Я получаю разные ошибки в зависимости от того, используется ли Pool или ThreadPool для get_attributes, я думаю, что это связано с тем, как память хранится / используется с помощью multiprocessing.

Но я надеюсь, что это можно решить с помощью *argv или что-то в этом роде.

1 Ответ

0 голосов
/ 17 марта 2020

Так что это работает:

def get_attributes(doc):
    with ThreadPool(2) as p:
        results = p.map(lambda x: doc[x], ["id", "created_utc", "title", "subreddit"])
        return results

# Map each document to the attribute function
def get_data(docs):
    with ThreadPool(2) as pool:
        results = pool.map(get_attributes, docs)
        return results

Но только с ThreadPool, использование Pool дало мне ошибку рассола. Я очень доволен результатом, но если кто-нибудь может предложить советы по дальнейшей оптимизации или объяснить, что такое рассол и почему мне пришлось использовать ThreadPool против Pool, я был бы очень рад услышать это!

...