辅助线程检查文件系统资源
helper thread checking filesystem resources
我是 运行 持续为请求提供服务的 http 服务器。
我想要单独的 "helper" 线程,检查文件系统中的目录是否可用。
如果资源消失了,那么我希望这个辅助线程将 return 值传给主线程,这样我就可以停止 http 服务器。
def main():
os.chdir(root)
server = HTTPServer(('0.0.0.0', 80), MyHandler)
server.serve_forever()
我在想
def foo(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo
# do some other stuff in the main process
return_val = async_result.get() # get the return value from your function.
如果 return_val == "stop"
则停止服务器
这是最好的方法吗?
如果你愿意放弃异步的东西(因为老实说我没有看到你需要它的理由)
你可以做
while foo():
server.handle_request()
而不是server.serve_forever()
如果您真的想异步进行检查,则需要显示更多有关您打算如何使用它的代码,您希望它不断检查吗?偶尔?由某些事件触发?
编辑:您仍然可以使用 while 循环,只需在里面添加 if
while True:
if foo():
server.handle_request()
else:
sleep(1) # or if foo is blocking (like when accessing the file system) you can just not sleep
无论如何,我最终还是签入了单独的线程,
就这么简单:
import threading
def background_check:
(...)
backgroundCheck = threading.Thread(target=backround_check, args=[directory])
backgroundCheck.start()
我是 运行 持续为请求提供服务的 http 服务器。 我想要单独的 "helper" 线程,检查文件系统中的目录是否可用。 如果资源消失了,那么我希望这个辅助线程将 return 值传给主线程,这样我就可以停止 http 服务器。
def main():
os.chdir(root)
server = HTTPServer(('0.0.0.0', 80), MyHandler)
server.serve_forever()
我在想
def foo(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo
# do some other stuff in the main process
return_val = async_result.get() # get the return value from your function.
如果 return_val == "stop"
则停止服务器这是最好的方法吗?
如果你愿意放弃异步的东西(因为老实说我没有看到你需要它的理由) 你可以做
while foo():
server.handle_request()
而不是server.serve_forever()
如果您真的想异步进行检查,则需要显示更多有关您打算如何使用它的代码,您希望它不断检查吗?偶尔?由某些事件触发?
编辑:您仍然可以使用 while 循环,只需在里面添加 if
while True:
if foo():
server.handle_request()
else:
sleep(1) # or if foo is blocking (like when accessing the file system) you can just not sleep
无论如何,我最终还是签入了单独的线程, 就这么简单:
import threading
def background_check:
(...)
backgroundCheck = threading.Thread(target=backround_check, args=[directory])
backgroundCheck.start()