[英]Using threading.Event to synchronize tasks in python
import socketserver
from http.server import SimpleHTTPRequestHandler
from threading import Timer, Event
from urllib.request import urlopen
class Responder( SimpleHTTPRequestHandler ):
evt = Event( )
def do_GET( self ):
print( 'req:', self.path )
if self.path == '/block':
Responder.evt.wait( )
self.respond( self.path )
elif self.path == '/unblock':
Responder.evt.set( )
self.respond( self.path )
else:
pass
# self.respond( self.path )
def respond( self, response ):
self.send_response( 200 )
self.send_header( 'Content-type', 'text/plain' )
self.end_headers( )
self.wfile.write( bytes( str( response ), 'utf8' ) )
# create and start server
httpd = socketserver.TCPServer( ( '', 80 ), Responder )
Timer( 0, lambda: httpd.serve_forever( ) ).start( )
# just request the stated URL
def req_async( url, sec_delay = 0 ):
Timer( sec_delay, lambda: print( 'resp:', urlopen( url ).read( ) ) ).start( )
req_async( 'http://localhost/block', 1 )
req_async( 'http://localhost/unblock', 2 )
req_async( 'http://localhost/foo' ) # closed connection without response !! but ..
# .. why not keep response stream open till I decide to write something on it ..
# .. or close it ?!
print( 0 )
This program creates a local server on port 80, and requests that server to (1) block after 1 second, and (2) unblock after 2 seconds. The class Responder has one threading.Event object, Responder.evt, which I want other requests to block/unblock on. When I get request on /block path, I wait on evt. When I get request on /unblock path, I release waiters. But only request (1) gets honored, and (2) is nowhere in the scenes :D Is it because (1) has blocked the server thread ?! Is it because evt is shared ? Can someone tell what happens there and why ?! TY ! :) And also, how to properly do this in case it does block the server thread. And also see the (3)rd request .. how to keep the response stream open ? So, all in all, [1] why python doesn't keep response stream open ? and [2] why request (2) is not getting logged ? Thank you and regards, Ankur
首先,我應該使用BaseHTTPRequestHandler
而不是SimpleHTTPRequestHandler
來實現處理程序。
其次,回答[2]
,以上兩個類一次將僅處理一個請求。 因此,上述程序中的請求(2)
在處理(1)
是無法處理的,但是由於(1)
被阻塞,所以無法記錄(2)
。
要使上述處理程序成為多線程,請參閱此答案 。
第三,回答[1]
,我仍然不確定,但我猜它的行為如下:
如果do_GET
/ do_POST
返回而沒有編寫響應,那么我猜該處理程序將關閉響應流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.