所谓士别三日当刮目相看,有一段时间没有注意看 StacklessPython 的邮件列表了,没想到现在 sandbox 中已经有了这么多有意思的代码了 ^_^ 。 最有意思的莫过于 examples/stacklesssocket.py 了,只要把标准库中的 socket 替换成stacklesssocket,然后使用 urllib 就自动成为异步的和StacklessPython兼容的。演示程序如下(摘自StacklessPython邮件列表):
import sys import stacklesssocket import stackless sys.modules["socket"] = stacklesssocket import urllib import time def download(uri): t1 = time.time() f = urllib.urlopen(uri) s = f.read() t2 = time.time() print "Downloaded", uri, "in", "%.1f" % (t2-t1), "seconds" return t2-t1 print " === Serial === " t1 = time.time() download("http://www.stackless.com/wiki/Tasklets") download("http://www.stackless.com/wiki/Channels") t2 = time.time() print " --->", t2-t1 print " === Parallel === " t1 = time.time() stackless.tasklet(download)("http://www.stackless.com/wiki/Tasklets") stackless.tasklet(download)("http://www.stackless.com/wiki/Channels") stackless.run() t2 = time.time() print " --->", t2-t1效果:
% spython async_fetch.py === Serial === Downloaded http://www.stackless.com/wiki/Tasklets in 2.6 seconds Downloaded http://www.stackless.com/wiki/Channels in 2.7 seconds ---> 5.34717988968 === Parallel === Downloaded http://www.stackless.com/wiki/Channels in 4.0 seconds Downloaded http://www.stackless.com/wiki/Tasklets in 5.4 seconds ---> 5.43875193596 % spython async_fetch.py === Serial === Downloaded http://www.stackless.com/wiki/Tasklets in 2.6 seconds Downloaded http://www.stackless.com/wiki/Channels in 2.7 seconds ---> 5.32963705063 === Parallel === Downloaded http://www.stackless.com/wiki/Channels in 2.2 seconds Downloaded http://www.stackless.com/wiki/Tasklets in 2.7 seconds ---> 2.71087312698还有 examples/threadchannels.py ,examples/threadscheduling.py 演示了 Stackless 如何与多线程一起使用! 还有更新过的 uthread 模块:libraries/uthread-ccp/uthread.py,这可是大名鼎鼎的 EVE-online 用到的东西哦 ^_^ 有时间再好好研究研究这些东西吧!
3 评论:
Stackless Python相关教程和资源
http://islab.org/stackless/
我用的是stackless模块
我有两个无限循环
一个线程是无限循环检测一个值的变化
另外一个是接受udp包
设置两个通道
one=stackless.channel()
two=stackless.channel()
def check():
two.recevie()
while 1:
if 检测值 a=1:
dosomething
else:
one.send('开始收包')
def udp():
one.receive()
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((loaclhost_ip,port))
while 1:
d,a=s.recvfrom(1024)
two.send('返回check')
开启线程
stackless.tasklet(check)()
stackless.tasklet(udp)()
stackless.tasklet(two.send)('开始检测')
stackless.run()
问题来了,如果我收不到数据,我永远无法跳回到check()检测值a了~
我要怎么做才能一边收包一边检测a的值呢??
两个a其实不是一个变量,只是顺手写的时候不小心的!
发表评论