how do I listen on a socket without sucking up all the CPU time?
Joshua Muskovitz
josh at open.com
Tue Oct 3 01:50:15 EDT 2000
Hi all,
I've got a worker thread which listens on an ICMP (ping) socket for replies
to pings that I send out (on the same socket from a different thread). All
of this code runs fine, but the socket is set to be non-blocking, so
recvfrom() returns immediately most of the time, and this thread runs like
mad, consuming all the available CPU time. It is definitely this thread --
when I don't create this particular thread, CPU usage drops back to normal.
Is there a way to somehow do this with signals of some sort? This needs to
run on NT/2000 as well as *nix.
Any other suggestions would also be gratefully welcomed...
-- josh
========= cut here for code =========
class PingThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.pid = os.getpid()
def run(self):
global KEEP_RUNNING
while KEEP_RUNNING:
try:
# attempt to receive a ping
pkt, who = PingScheme.icmpSocket.recvfrom(512)
ipPacket = ip.Packet(pkt)
icmpPacket = icmp.Packet(ipPacket.data)
now = time.time()
if icmpPacket.type == icmp.ICMP_ECHOREPLY:
if icmpPacket.id == self.pid:
# this means the ping is for us
[handler here snipped]
except socket.error:
pass
except ValueError:
pass
except KeyboardInterrupt:
KEEP_RUNNING = 0
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 80,000 Newsgroups - 16 Different Servers! =-----
More information about the Python-list
mailing list