Python: Why does this non-blocking call to recv block?
I have the following code in the $init call of a thread:
self.conn = copy.deepcopy(conn)
self.conn.setblocking(0)
conn is a socket and is passed as an argument to $init Every thread recieves a unique socket. In the run method I have:
self.running = True
self.conn.send("Connected")
print self.name, "has 开发者_StackOverflowa timeout of", self.conn.gettimeout()
while self.running:
try:
now = self.conn.recv(8192)
print "Recieved:", now, "\n\tFrom:", self.name
self.process(now)
except socket.error:
raise
print "hi from", self.name
time.sleep(1)
The timeout is printed as 0.0, but "hi from threadname" only printed out when a message is recieved and the exception is never raised! It looks as if the recv method blocks, but why would it do that?
Propably because recv is reading from file and I/O is blocking? (sockets are files too as you may know) :)
Look here: python socket.recv/sendall call blocking for more info :)
精彩评论