可爱的 Python: 用 Python 生成器实现“轻便线程”
2007-03-29 12:04:49 来源:WEB开发网清单 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
更多精彩
赞助商链接