python - 如何管理 python 线程结果?

标签 python multithreading arrays

我正在使用这段代码:

def startThreads(arrayofkeywords):
    global i
    i = 0
    while len(arrayofkeywords):
        try:
            if i<maxThreads:
                keyword = arrayofkeywords.pop(0)
                i = i+1
                thread = doStuffWith(keyword)
                thread.start()
        except KeyboardInterrupt:
            sys.exit()
    thread.join()

对于 python 中的线程,我几乎完成了所有工作,但我不知道如何管理每个线程的结果,在每个线程上我都有一个字符串数组作为结果,我如何才能安全地将所有这些数组连接成一个?因为,如果我尝试写入一个全局数组,两个线程可能会同时写入。

最佳答案

首先,您实际上需要保存所有 那些thread 对象以在它们上调用join()。正如所写,您只保存最后一个,并且只有在没有异常的情况下才保存。

进行多线程编程的一种简单方法是为每个线程提供其运行所需的所有数据,然后让它不写入该工作集之外的任何内容。如果所有线程都遵循该准则,它们的写入将不会相互干扰。然后,一旦一个线程完成,仅主线程将结果聚合到一个全局数组中。这被称为“fork/join 并行性”。

如果您对 Thread 对象进行子类化,则可以为其提供空间来存储该返回值,而不会干扰其他线程。然后你可以这样做:

class MyThread(threading.Thread):
    def __init__(self, ...):
        self.result = []
        ...

def main():
    # doStuffWith() returns a MyThread instance
    threads = [ doStuffWith(k).start() for k in arrayofkeywords[:maxThreads] ]
    for t in threads:
        t.join()
        ret = t.result
        # process return value here

编辑:

看了一圈,好像是上面的方法isn't the preferred way to do threads in Python .上面更多的是线程的 Java 风格模式。相反,您可以执行以下操作:

def handler(outList)
    ...
    # Modify existing object (important!)
    outList.append(1)
    ...

def doStuffWith(keyword):
    ...
    result = []
    thread = Thread(target=handler, args=(result,))
    return (thread, result)

def main():
    threads = [ doStuffWith(k) for k in arrayofkeywords[:maxThreads] ]
    for t in threads:
        t[0].start()
    for t in threads:
        t[0].join()
        ret = t[1]
        # process return value here

关于python - 如何管理 python 线程结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3239617/

相关文章:

java - 如何检查某些事件中经过了多少毫秒(java)

arrays - 数组在代码结束后保留​​值

Python帮助无法弄清楚单元测试失败的原因

python - 多线程模式下的 aiosqlite 和 SQLite 有什么区别?

python - 将二维列表写入JSON文件

c++ - volatile 和多线程?

java - 如何在数组中插入一系列元素?

php - 我如何重组这个数组以将数据压缩成 PHP 中更有用的格式?

python - 你如何组织 Python 模块?

python - 是什么导致我的 Python 程序使用 opencv 耗尽内存?