使用gevent Greenlets时出现奇怪的行为

时间:2017-08-10 06:01:48

标签: python python-3.x gevent greenlets

我是异步编程的新手。我正在做一个小POC,我想看看greenlets对共享对象的行为。我写了这段代码 -

from gevent import monkey, sleep
from gevent import Greenlet
monkey.patch_all(thread=False, socket=False)

class Events:
    def __init__(self):
        self.num = 0
        self.limit = 10
        self.bulk_records = []

    def start(self, task_number=0):
        count = 0
        print("Task: %s started" % task_number)
        while count != 10:
            self.bulk_records.append(task_number)
            sleep(0.1)
            if len(self.bulk_records) == self.limit:
                print("%s, Task %s, outputting list: %s" % (self.num, task_number, self.bulk_records))
                self.bulk_records[:] = []
                self.num += 1
            count += 1
        print("Task - %s, count - %s" % (task_number, count))

def run_test():
    event = Events()
    tasks = [Greenlet.spawn(event.start, i) for i in range(5)]
    print("Num tasks - %s" % len(tasks))
    [task.run() for task in tasks]
    print("End")

if __name__ == '__main__':
    run_test()

它提供以下输出: -

Num tasks - 5
Task: 0 started
Task: 1 started
Task: 2 started
Task: 3 started
Task: 4 started
0, Task 0, outputting list: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
1, Task 0, outputting list: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
2, Task 0, outputting list: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
3, Task 0, outputting list: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
4, Task 0, outputting list: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
Task - 0, count - 10
Task: 1 started # This is not expected
Task - 1, count - 10
Task - 2, count - 10
Task - 3, count - 10
Task - 4, count - 10
5, Task 1, outputting list: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Task - 1, count - 10
End

Process finished with exit code 0

代码按预期工作,但最终发生了一些奇怪的事情,任务1再次启动,相应的函数start再次执行。

不确定这是否是有效行为,或者我在代码中缺少的内容,以防止Greenlet重新开始。

谢谢是提前

1 个答案:

答案 0 :(得分:1)

与线程API相反,线程API需要创建一个线程对象并调用start()方法,gevent.spawn既进行Greenlet实例化,又安排Greenlet在一次调用中运行。

因此,不需要在greenlet对象上调用run()(在大多数情况下可能非常错误)。

等待完成的任务由joinall(list of greenlets)完成。调用之后,所有的绿色组件都已准备就绪(已死,是否成功)。