最新消息:20210917 已从crifan.com换到crifan.org

【已解决】尝试使用gevent的spawn去新创建协程去异步执行

Flask crifan 3230浏览 0评论

折腾:

【已解决】Flask中的线程或进程间通信

期间,去学习,如何使用gevent的spawn去新创建协程,去异步执行对应的代码

搜:

gevent spawn

参考

gevent – basic utilities — gevent 1.2a2.dev0 documentation

g = Greenlet(myfunction, ‘arg1’, ‘arg2’, kwarg1=1)
g.start()
或:
g = Greenlet.spawn(myfunction, ‘arg1’, ‘arg2’, kwarg1=1)

Python gevent学习笔记 2 – 冯伟刚的个人空间 – 开源中国社区

关于gevent的一些理解(一) – 小明明s à domicile

Gevent指南

gevent – 廖雪峰的官方网站

Probability | G_will’s Blog

【总结】

然后是可以直接使用:

def listenWsAndSendMsg(ws, userId):
    gLog.debug(“use redis to listen ws=%s and send message for userId=%s”, ws, userId)
    curPubSub = redisConnection.pubsub()
    gLog.debug(“curPubSub=%s”, curPubSub)
    # curPubSub=<redis.client.PubSub object at 0x7fd17176d950>
    。。。。。
@sockets.route(‘/users/<userId>/<accesstoken>’)
def userWebsocket(ws, userId, accesstoken):
    wsRoutine = gevent.spawn(listenWsAndSendMsg, ws, userId)
    gLog.debug(“wsRoutine=%s”, wsRoutine)

然后对应的log是:

wsRoutine=<Greenlet at 0x7fb4f96c7190: listenWsAndSendMsg(<geventwebsocket.websocket.WebSocket object at 0x7, u’user-bb22f24e-3c27-4e7b-867a-b855e139b295’)>
wsRoutine=<Greenlet at 0x7fb4f8148550: listenWsAndSendMsg(<geventwebsocket.websocket.WebSocket object at 0x7, u’user-cc680b0a-8d04-4f2b-8ad9-c6fefb527861′)>

-》

可见,对于(来自不同用户的)不同的request去访问此处的websocket的端口:

所生成的greenlet是不同的

-》

这样就确保了:

对于不同的用户,生成了不同的coroutine去处理对应的事情

-》此处就是:

while去循环去listen接受来自其他地方所publish的事件,去调用此ws去通知相应的用户,发送对应的消息。

转载请注明:在路上 » 【已解决】尝试使用gevent的spawn去新创建协程去异步执行

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
99 queries in 0.205 seconds, using 23.35MB memory