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

时间:2014-10-23 10:56:25

标签: python multithreading timeout threadpool

如何使用超时杀死多个线程?我在这里编写简单版本的脚本。我想运行两个线程,将params映射到函数。如果超时结束 - 我想终止所有线程并转到循环的下一次迭代。但现在,我得到了我没想到的结果:

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

实际结果:

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

test 1 [6, 2, 1]
test 1 [6, 2, 1, 1]
test 1 [6, 2, 1, 1, 1]
test 1 [6, 2, 1, 1, 1, 1]
err
LOOP: 2
test 6 [6]
test 2 [6, 2]
test 1 [6, 2, 1]
test 1 [6, 2, 1, 1]
test 1 [6, 2, 1, 1, 1]
test 1 [6, 2, 1, 1, 1, 1]
err
LOOP: 3
test 6 [6]
test 2 [6, 2]
test 1 [6, 2, 1]
test 1 [6, 2, 1, 1]
test 1 [6, 2, 1, 1, 1]
test 1 [6, 2, 1, 1, 1, 1]
err
LOOP: 4
test 6 [6]test 2 [6, 2]

test 1 [6, 2, 1]
test 1 [6, 2, 1, 1]
test 1 [6, 2, 1, 1, 1]
test 1 [6, 2, 1, 1, 1, 1]
err

预期结果:

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

... 我该如何解决这个问题?

0 个答案:

没有答案