Demo entry 6412562

semaphore

   

Submitted by anonymous on May 25, 2017 at 11:47
Language: Python. Code size: 348 Bytes.

sema = Semaphore(3)
# 创建信号量限制访问资源的线程数为3, 同时只能最多有三个线程访问
# 执行一次acquire,信号量减1,release加1,计数器为0时,线程调用acquire会阻塞,直到执行一次release
def foo(tid):
    with sema:
    # with 可在代替 acquire 和 release, 首先执行acquire,然后release
        print '{} acquire sema'.format(tid)
        wt = random() * 2
        time.sleep(wt)
    print '{} release sema'.format(tid)

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).