It may be a silly question, but it's been bothering me for a long time. When I create threads in a program, the number in the thread name keeps growing.
from threading import Thread, current_thread
from time import sleep
def worker():
print(f'{current_thread().name} running')
for i in range(10):
t = Thread(target=worker)
t.start()
sleep(.1)
print(t.is_alive())
The output is:
Thread-1 (worker) running
False
Thread-2 (worker) running
False
Thread-3 (worker) running
...
My question is, if a program keeps creating threads, does that number go up infinitely? For example, use ThreadingTcpServer to create a multi-threaded socket server:
import socketserver
from threading import current_thread
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
data = self.request.recv(1024)
print(f'{current_thread().name} receive: {data.decode()}')
conn.sendall(data)
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 9999), MyServer)
server.serve_forever()
Each time a request is received, the number gets bigger:
Thread-1 receive: hello
Thread-2 receive: world
...
If the server runs forever, does the number go up infinitely? Will the memory usage be affected?