python - 使用多线程(使用并发.futures)在Python中添加列表会导致偏移行

标签 python python-3.x

我是一名 Python 新手爱好者,并已开始使用并发.futures 尝试多线程。

每个单独的线程都应该分析 HTML 文件,然后将某些项目附加到列表中。所有线程完成后,结果列表将写入 CSV 文件。

令人惊讶的结果是,行的某些部分似乎在列表中偏移了 1 行,例如:

预期结果:

caseList = [
   [a1, a2, a3],
   [b1, b2, b3],
   [c1, c2, c3],
   [d1, d2, d3],
]

实际结果:

caseList = [
   [a1, a2, a3],
   [b1, a2, a3],
   [c1, b2, b3],
   [d1, c2, c3]
]

其中的字母恰好代表一个应该由一个线程分析的 HTML 文件。 我无法准确指出它发生变化的位置,但它一开始是正确的,但随后某些行部分包含应属于前一行的项目。

我已经阅读了有关竞争条件和锁定的内容,但也阅读了 list.append 应该是线程安全的评论。所以不完全确定这里发生了什么。

这是我的代码:

caseList = []

with concurrent.futures.ThreadPoolExecutor() as executor:
    results = [executor.submit(searchCase, filename, pattern) for filename in logContents]
    for f in concurrent.futures.as_completed(results):
        caseList.append(f.result())
        print(f.result())

我在这里明显做错了什么吗?

最佳答案

这个问题的回答在 Avoiding race condition while using ThreadPoolExecutor

您不应期望从生成器返回有序结果 for 循环:

for f in concurrent.futures.as_completed(results):

存在用于控制由concurrent.futures.as_completed(results)创建的生成器。然而,结果是可用的。由于它是异步执行,因此结果将是无序的。

您可以在此处的 current.future 文档中查看此说明:

concurrent.futures.as_completed(fs, timeout=None)

Returns an iterator over the Future instances (possibly created by different Executor instances) given by fs that yields futures as they complete (finished or canceled futures). Any futures given by fs that are duplicated will be returned once. Any futures that completed before as_completed() is called will be yielded first. The returned iterator raises a concurrent.futures.TimeoutError if next() is called and the result isn’t available after timeout seconds from the original call to as_completed(). timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time.

希望这有帮助

关于python - 使用多线程(使用并发.futures)在Python中添加列表会导致偏移行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941301/

相关文章:

Python:在巨大的文本中替换单词

python-3.x - 在 Python 3.4 与 Python 3.5 中使用类型提示会产生语法错误

python - 我如何使用矢量来实现与此相同的效果

python-3.x - python : Feature Matching + Homography to find Multiple Objects

python - 在 Python 3 中将二进制文件转换为字节数组

python-3.x - 无法在 Matplotlib 2.2.2 中使用 contourf 更改填充密度

python - python 中的 Tornado 图表和 p10-p90 (matplotlib)

python - 用一种方法监听 2 个不同的击键 (Pynput)

python - 如果 JSON 字符串中不存在属性,如何返回空字符串?

python - 缩短在字典中打印单个值