关于gevent的微线程“eventlet”同步问题

理论上讲,Python是不存在线程安全问题的,由于GIT么,但是这是有前提的:sleep,I/O导致的wait都可能会引发线程安全隐患。

同理,gevent是基于事件驱动模型的,就不太可能是线程安全的。

gevent.coros.Semaphore提供了信号量的功能,可以是n个哦!

semaphore.acquire() -> 获取“锁”
semaphore.release() -> 释放“锁”

gevent的文档写的真简介啊,于是测试了个基本的同步方法:同步某一关键区,供大家参考:

'''
Created on Sep 20, 2011

@author: liheyuan
'''

from gevent.coros import Semaphore
from gevent.greenlet import Greenlet
from gevent import sleep
import random

semaphore = Semaphore()

def test():
    #critical start!!!
    semaphore.acquire()
    for i in xrange(100):
        print "1"
        sleep(random.random())
        print "2"
    semaphore.release()
    #critical end!!!

if __name__ == "__main__":
    print "Hello World"
    print "Before ,", cnt
    gs = []
    for i in xrange(100):
        gs.append(Greenlet.spawn(test))
    for g in gs:
        g.join()
    print "After ,", cnt

Leave a Reply

Your email address will not be published. Required fields are marked *