pis*_*lis 7 python performance multithreading
这个问题涉及性能惩罚,这些惩罚可能会或可能不会因在Web服务器上存在大量睡眠python线程而产生.
背景:我正在使用django/satchmo实现在线商店.要求延迟付款.客户可以预订产品并允许第三方在以后付款(通过随机且唯一的URL).
为了处理未保留的项目,我正在创建一个线程,该线程将在预订时间内休眠,然后在唤醒时删除预订/标记产品.它看起来像这样:
#Reserves a product when it is placed in the cart
def reserve_cart_product(product):
log.debug("Reserving %s" % product.name)
product.active = False
product.featured = False
product.save()
from threading import Timer
Timer(CART_RESERVE_TIME, check_reservation, (product,)).start()
Run Code Online (Sandbox Code Playgroud)
在过期后剔除唯一的URL时,我使用相同的技术,只有Timer睡眠时间更长(通常为5天).
那么,我对你的问题如下:
是否有大量的睡眠线会严重影响性能?是否有更好的技术可以在将来的某个时间安排一次性事件.如果可能的话,我想在python中保留它; 没有打电话at或cron通过sys.
该网站的流量并不高; 每周订购产品的(慷慨)上限约为100.结合购物车预订,这可能意味着任何时候都有100多个睡眠线程.我会后悔以这种方式安排任务吗?
谢谢
我认为没有理由不这样做.Timer的底层代码(在threading.py中)只使用time.sleep.一旦它等待一段时间,它基本上会运行一个带有time.sleep(0.05)的循环.这应该导致CPU使用率基本上为0%,即使有数百个线程.这是一个简单的例子,我注意到python进程的0%cpu使用率:
import threading
def nothing():
pass
def testThreads():
timers = [threading.Timer(10.0, nothing) for _ in xrange(881)]
print "Starting threads."
map(threading.Thread.start, timers)
print "Joining threads."
map(threading.Thread.join, timers)
print "Done."
if __name__ == "__main__":
testThreads()
Run Code Online (Sandbox Code Playgroud)
真正的问题是你可能无法实际启动太多线程.在我的64位4GB系统上,我只能在出现错误之前启动881个线程.但是,如果你真的只有几百个,我无法想象它会起作用.