Python:为什么这个对 recv 的非阻塞调用会阻塞?
我在线程的 $init 调用中有以下代码:
self.conn = copy.deepcopy(conn)
self.conn.setblocking(0)
conn 是一个套接字,并作为参数传递给 $init 每个线程都会收到一个唯一的套接字。在 run 方法中,我有:
self.running = True
self.conn.send("Connected")
print self.name, "has a 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)
超时打印为 0.0,但“hi from threadname”仅在收到消息时打印,并且永远不会引发异常!看起来好像recv方法会阻塞,但为什么会这样做呢?
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 a 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是因为 recv 正在从文件读取并且 I/O 阻塞? (您可能知道,套接字也是文件):)
请看这里:python socket.recv/ sendall 呼叫阻塞 了解更多信息:)
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 :)