WEB开发网
开发学院软件开发Python 可爱的 Python: 用 Python 生成器实现“轻便线程”... 阅读

可爱的 Python: 用 Python 生成器实现“轻便线程”

 2007-03-29 12:04:49 来源:WEB开发网   
核心提示: 清单 2. microthreads.py 示例脚本from __future__import generatorsimport sys, timethreads = []TOTALSWITCHES =10**6NUMTHREADS=10**5def null_factory():def

清单 2. microthreads.py 示例脚本    
     
     from
    
     __future__
    
    
     
     import
    
     generators
    
    
     
     import
    
     sys, time
threads = []
TOTALSWITCHES =
    
    10**6
NUMTHREADS  =
    
    10**5
    
    
     
     def
    
     null_factory():
  
    
    
     
     def
    
     empty():
    
    
    
     
     while
    
    
    
    1:
    
    
     
     yield
    
     None
  
    
    
     
     return
    
     empty()
    
    
     
     def
    
     quitter():
  
    
    
     
     for
    
     n
    
    
     
     in
    
     xrange(TOTALSWITCHES/NUMTHREADS):
    
    
    
     
     yield
    
     None
    
    
     
     def
    
     scheduler():
  
    
    
     
     global
    
     threads
  
    
    
     
     try
    
    :
    
    
    
     
     while
    
    
    
    1:
      
    
    
     
     for
    
     thread
    
    
     
     in
    
     threads: thread.next()
  
    
    
     
     except
    
     StopIteration:
    
    
    
     
     passif
    
     __name__ ==
    
    
     
     "__main__"
    
    :
  
    
    
     
     for
    
     i
    
    
     
     in
    
     range(NUMTHREADS):
    threads.append(null_factory())
  threads.append(quitter())
  starttime = time.clock()
  scheduler()
  
    
    
     
     print
    
    
    
    
     
     "TOTAL TIME:  "
    
    , time.clock()-starttime
  
    
    
     
     print
    
    
    
    
     
     "TOTAL SWITCHES:"
    
    , TOTALSWITCHES
  
    
    
     
     print
    
    
    
    
     
     "TOTAL THREADS: "
    
    , NUMTHREADS
   

上一页  1 2 3 4 5 6 7 8  下一页

Tags:可爱 Python Python

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接