快乐学习
前程无忧、中华英才非你莫属!

Python-异步编程-gevent-8

锁和信号量

信号量是一种低级同步原语,它允许 greenlet 协调和限制并发访问或执行。信号量公开了两个方法,acquire和release的信号量已经被获取和释放被称为绑定的旗语的次数之间的差异。如果信号量边界达到 0,它将阻塞,直到另一个 greenlet 释放其获取。

from gevent import sleep
from gevent.__semaphore import BoundedSemaphore
from gevent.pool import Pool

sem = BoundedSemaphore(2)

def worker1(n):
    sem.acquire()
    print('Worker %i acquired semaphore' % n)
    sleep(0)
    sem.release()
    print('Worker %i released semaphore' % n)

def worker2(n):
    with sem:
        print('Worker %i acquired semaphore' % n)
        sleep(0)
    print('Worker %i released semaphore' % n)

pool = Pool()
pool.map(worker1, range(0, 2))
pool.map(worker2, range(3, 6))

# Worker 0 acquired semaphore
# Worker 1 acquired semaphore
# Worker 0 released semaphore
# Worker 1 released semaphore
# Worker 3 acquired semaphore
# Worker 4 acquired semaphore
# Worker 3 released semaphore
# Worker 4 released semaphore
# Worker 5 acquired semaphore
# Worker 5 released semaphore

线程局部变量

Gevent 还允许您指定 greenlet 上下文的本地数据。在内部,这是作为全局查找实现的,它寻址由 greenlet 的getcurrent()值作为键的私有命名空间。

import gevent
from gevent.local import local

stash = local()

def f1():
    stash.x = 1
    print(stash.x)

def f2():
    stash.y = 2
    print(stash.y)
    try:
        stash.x
    except AttributeError:
        print("x is not local to f2")

g1 = gevent.spawn(f1)
g2 = gevent.spawn(f2)

gevent.joinall([g1, g2, g2])
打赏

未经允许不得转载:同乐学堂 » Python-异步编程-gevent-8

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

特别的技术,给特别的你!

联系QQ:1071235258QQ群:367203382
error: Sorry,暂时内容不可复制!