gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:49:11 26 4
gpt4 key购买 nike

我是一名 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com