python模块学习(threading模块中的Semaphore类和BoundedSemaphore类)

学习版本3.5.2

Semaphore类和BoundedSemaphore类都是信号量类,每次有线程获得信号量的时候(即acquire())计数器-1,释放信号量时候(release())计数器+1,计数器为0的时候其它线程就被阻塞无法获得信号量。当计数器为设定好的上限的时候BoundedSemaphore就无法进行release()操作了,Semaphore没有这个限制检查。

#/usr/bin/python3
# -*- utf-8 -*-
#学习版本3.5.2

import threading
import time

num = 2

def test():
    global num
    n = se.acquire()
    num -= 1
    print("Semaphore acquire:",num)
    time.sleep(1)
    se.release()
    num += 1
    print("Semaphore release:",num)


if __name__ == "__main__":
    se = threading.BoundedSemaphore(num)

    tlist = []

    for i in range(5):
        t = threading.Thread(target=test)
        tlist.append(t)

    for i in tlist:
        i.start()

    print("main")

运行结果

Semaphore acquire: 1
Semaphore acquire: 0
main
Semaphore release: 1
Semaphore release: 2
Semaphore acquire: 1
Semaphore acquire: 0
Semaphore release: 1
Semaphore release: 2
Semaphore acquire: 1
Semaphore release: 2

当使用Semaphore时候,可以直接调用release()使得内置的计数器就直接加1,BoundedSemaphore这样的操作就会抛出ValueError。

#/usr/bin/python3
# -*- utf-8 -*-
#学习版本3.5.2

import threading
import time

num = 2

def test():
    global num
    n = se.acquire()
    num -= 1
    print("Semaphore acquire:",num)
    time.sleep(1)
    se.release()
    num += 1
    print("Semaphore release:",num)


if __name__ == "__main__":
    se = threading.Semaphore(num)
    se.release()

    tlist = []

    for i in range(5):
        t = threading.Thread(target=test)
        tlist.append(t)

    for i in tlist:
        i.start()

    print("main")

运行结果就是3个线程3个线程一起跑,就像threading.Semaphore(3)的效果一样

Semaphore acquire: 1
Semaphore acquire: 0
Semaphore acquire: -1
main
Semaphore release: 0
Semaphore release: 1
Semaphore acquire: 1
Semaphore release: 2
Semaphore acquire: 0
Semaphore release: 1
Semaphore release: 2


你可能感兴趣的:(python学习笔记,模块学习)