Python多线程但使用对象实例

2024-09-20 22:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望你能帮助我

我有一个msgList,包含msg个对象,每个对象都有poscontent属性。 然后我有一个函数posClassify,它创建了一个SentimentClassifier对象,它通过这个msgList进行迭代,并执行msgList[i].pos = clf.predict(msgList[i].content),作为clf的一个实例

def posClassify(msgList):
    clf = SentimentClassifier()
    for i in tqdm(range(len(msgList))):
        if msgList[i].content.find("omitted") == -1:
            msgList[i].pos = clf.predict(msgList[i].content)

我想用多重处理来计算这个。我已经读到,您创建了一个池,并调用了一个函数,其中包含要传递该函数的参数列表,就这样。我认为该函数必须类似于保存图像或在不同的内存空间中工作,而不像我的函数,在我的函数中,您要修改相同的msg对象,并且必须使用该SentimentClassifier对象(初始化大约需要10秒左右)

我的想法是创建cpu_cores-1进程,每个进程使用一个SentimentClassifier实例,然后每个进程开始使用带有自己分类器的msg列表,但我不知道如何实现这一点。我还考虑过使用二进制信号量创建线程,每个线程调用自己的分类器,然后等待信号量更新msg对象中的pos值,但仍然无法理解


Tags: 对象实例函数pos列表进程分类器msg
1条回答
网友
1楼 · 发布于 2024-09-20 22:23:56

您可以在Python中使用来自futures模块的ProcessPoolExecutor

{}是

An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine

你可以在Python docs找到更多信息

这里是实现并发性的示例代码,假设每个msgList[i]i != j时独立于msgList[j]

from concurrent import futures

def posClassify(msg, idx, clf):
    return idx, clf.predict(msg.content)

def classify(msgList):
    clf = SentimentClassifier()

    calls = []

    executor = futures.ProcessPoolExecutor(max_workers=4)
    for i in tqdm(range(len(msgList))):
        if msgList[i].content.find("omitted") == -1:
            call = executor.submit(posClassify, msgList[i], i, clf)
            calls.append(call)

    # wait for all processes to finish
    executor.shutdown()

    # assign the result of individual calls to msgList[i].pos
    for call in calls:
        result = call.result()
        msgList[result[0]].pos = result[1]

为了执行代码,只需调用classify(msgList)函数

相关问题 更多 >

    热门问题