在python中如何使用超时连接多个线程?

2024-04-26 22:45:23 发布

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

如何在超时的情况下杀死多个线程?我在这里写我的脚本的简单版本。我要运行两个线程,将参数映射到函数。如果超时结束-我想终止所有线程并移到循环的下一个迭代。但现在,我得到了出乎意料的结果:

res = []
arr = [6,1,1,1,1,2,3]
def test(n):
    time.sleep(n)
    res.append(n)
    print("test" + str(res))

i = 0
while i < 10:

    res = []
    print("LOOP: " + str(i))
    pool = ThreadPool(2)
    result = pool.map_async(test, arr)
    try:
        updates = result.get(timeout=5)
        pool.close()
        pool.join()
    except Exception:
        print("err")
        pool.terminate()
        i = i + 1
        continue


    print("end")
    i = i + 1

实际结果:

^{pr2}$

预期结果:

LOOP: 0
test 1 [1]
test 1 [1, 1]
test 1 [1, 1, 1]
test 1 [1, 1, 1, 1]
test 1 [1, 1, 1, 1, 2]
test 1 [1, 1, 1, 1, 2, 3]
err
LOOP: 1
test 1 [1]
test 1 [1, 1]
test 1 [1, 1, 1]
test 1 [1, 1, 1, 1]
test 1 [1, 1, 1, 1, 2]
test 1 [1, 1, 1, 1, 2, 3]
err

。。。 我怎么解决这个问题?在


Tags: 函数test版本脚本loop参数情况res