Tomas Bruckner
Tomas Bruckner

Reputation: 728

How properly close thread in Python

I'm having trouble understanding threads in Python. I have this program:

import _thread, time

def print_loop():
    num = 0
    while 1:
        num = num + 1
        print(num)
        time.sleep(1)

_thread.start_new_thread(print_loop, ())

time.sleep(10)

And my question is if I need to close the thread print_loop, because it looks to me that both threads end when the main thread ends. Is this proper way to handle threads?

Upvotes: 3

Views: 5954

Answers (1)

Krumelur
Krumelur

Reputation: 32497

First, avoid using the low-level API unless you absolutely have to. The threading module is preferred over _thread. In general in Python, avoid anything starting with an underscore.

Now, the method you are looking for is called join. I.e.

import time
from threading import Thread

stop = False

def print_loop():
    num = 0
    while not stop:
        num = num + 1
        print(num)
        time.sleep(1)

thread = Thread(target=print_loop)
thread.start()

time.sleep(10)

stop = True
thread.join()

Upvotes: 6

Related Questions