在线程中阻塞语句导致杀死线程的时间更长?

时间:2015-05-15 20:40:36

标签: python multithreading python-2.7

我在Python中启动一个自定义线程,它应该定期打印一些有关当前进度的统计信息。一旦用户表示停止程序,就必须杀死所有线程。到目前为止,这是有效的,但对于所述的线程。

def print_statistics(thread_id):
    print "Thread {} started (information thread)".format(thread_id)

    # thread_stop_event is of type threading.Event
    while (not thread_stop_event.is_set()):

        print "important information"
        time.sleep(5) # print some information every five seconds


    print "Thread {} is terminating - Bye".format(thread_id)

我使用了一个用户指示退出程序时未设置的threading.Event。然后守护进程完成,线程自动停止。

我知道time.sleep()。因为它只阻止五秒钟,所以在经过这段时间之后最坏的情况下应该杀死线程。

现在我做了以下观察:用户等待命令杀死所有线程的时间越长,杀死print_statistics所需的时间越长。为什么?不应该花费最多五秒钟吗?

修改

这是处理所有线程的主要方法。首先启动工作线程,并且最终提供信息线程,该信息线程向用户提供当前统计信息。

def run():
    running_threads = list()

    # start working threads
    for i in range(0, max_threads):
        t = Thread(target=worker_thread, args=(i,))
        running_threads.append(t)
        running_threads[i].start()

    # start thread that provides user with statistical information
    inf_thread = Thread(target=print_statistics, args=(max_threads,))
    inf_thread.start()

    # wait for user interrupt
    while True:
        input = raw_input("\nType \"quit\" to quit!\n")
        if input == "quit":
            thread_stop_event.set() # inform all threads to terminate
            break
        else:
            print "Input not recognized. Try again!"

1 个答案:

答案 0 :(得分:0)

我不知道问题是什么,但你应该使用

while not thread_stop_event.wait(5):
    print "important information"