Naatan
Naatan

Reputation: 3474

Clear threads in python?

I'm trying to set up a very simple UDP socket server with python that accepts asynchronous connections. Now I have never used Python much before but I like the language a lot from what I've read about it, which is why I am using it for this test.

I am following the example given here:

http://docs.python.org/library/socketserver.html#asynchronous-mixins

I already have it successfully running as a UDP server (the example is TCP), with very few modifications so it's almost exactly the same as in that example. The only thing I don't get is that it keeps creating new threads for every connection.

Now I may just be miss understanding the concept of threads, which is why I'm asking my question here, but shouldn't it clear up unused threads and re-use them? Or is it already doing that and it's simply an incremental counter indicating the number that I shouldn't care too much about?

So basically, with the given example, can I safely run this (as a test) for hours at an end, with thousands of connections (not concurrently, but over time) without any problems or will it start thousands of threads that linger on for far longer than they should?

Thanks

Upvotes: 2

Views: 1309

Answers (1)

nosklo
nosklo

Reputation: 223102

No need for threads. Use real asynchronous IO. It scales a lot better. Threads to wait for IO just add overhead, no performance gain.

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class Echo(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)
        self.transport.write(data, (host, port))

reactor.listenUDP(9999, Echo())
reactor.run()

Upvotes: 6

Related Questions