您的当前位置:首页正文

你知道Python有一个并发编程库吗?goless

来源:花图问答

前言

使用goless库,您可以用Python的Go语言风格编写并发程序。goess提供了通道、select和goutines函数,这些函数允许您使用Go语言的漂亮而优雅的并发编程模型,但使用的是您习惯的Python方式。goess构建在gevent、pypy或stackless python上,可用于pypy、cpython和scratch python解释器,支持python 2.6到3.4

示例代码:

"""
A really simple example to use when demonstrating goless.
"""
from __future__ import print_function

import goless


def simple():
    channel = goless.chan()

    def goroutine():
        while True:
            value = channel.recv()
            channel.send(value ** 2)
    goless.go(goroutine)

    for i in range(2, 5):
        channel.send(i)
        squared = channel.recv()
        print('%s squared is %s' % (i, squared))

    # Output:
    # 2 squared is 4
    # 3 squared is 9
    # 4 squared is 16

if __name__ == '__main__':
    simple()

虽然这个库很少会用到, 大家今天还是为大家介绍一下,如果你继续深入学习,总会碰各种各样的问题,如果刚好用上这个库,那是再好不过了,