How to close a thread when multithreading? [duplicate]

To terminate an Thread controlled, using a threadsafe threading.Event():

import threading, time

def Thread_Function(running):
    while running.is_set():
        print('running')
        time.sleep(1)

if __name__ == '__main__':
    running = threading.Event()
    running.set()

    thread = threading.Thread(target=Thread_Function, args=(running,))
    thread.start()

    time.sleep(1)
    print('Event running.clear()')
    running.clear()

    print('Wait until Thread is terminating')
    thread.join()
    print("EXIT __main__")

Output:

running  
running  
Event running.clear()  
Wait until Thread is terminating  
EXIT __main__

Tested with Python:3.4.2


Online Demo: reply.it

Leave a Comment