亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

threading 之 semaphore信號量

發布時間:2020-06-29 15:02:05 來源:網絡 閱讀:454 作者:windcharger 欄目:編程語言

semaphore信號量的簡單代碼演示

import threading
import logging
import time

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

def worker(s:threading.Semaphore):
    logging.info('in sub thread')
    logging.info(s.acquire())   # 獲取信號量,計數器 -1
    logging.info('sub thread over')

s = threading.Semaphore(3)   # 創建3個信號量計數器
logging.info(s.acquire())
print(s._value)    # 看看現在信號量的內的數值是多少
logging.info(s.acquire())
print(s._value)
logging.info(s.acquire())
print(s._value)

threading.Thread(target=worker, args=(s, )).start()

time.sleep(2)

logging.info(s.acquire(False))    # 不阻塞,若獲取不到信號量,則為False
logging.info(s.acquire(timeout=10))   # 設置超時時間,等待超時時間過了還未獲取到信號,返回值為False

# 釋放
logging.info('released')
s.release()   # 釋放信號量,計數器i + 1

簡單的資源池演示

import threading
import logging
import random

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

class Conn:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

class Pool:
    def __init__(self, count:int):
        self.count = count
        self.pool = [ self._connect('conn-{}'.format(x)) for x in range(self.count)]

    def _connect(self, conn_name):
        return Conn(conn_name)

    def get_conn(self):
        conn = self.pool.pop()
        return conn

    def return_conn(self, conn:Conn):
        self.pool.append(conn)

pool = Pool(3)

def worker(pool:Pool):
    conn = pool.get_conn()
    logging.info(conn)
    threading.Event().wait(random.randint(1,4))
    pool.return_conn(conn)

for i in range(6):
    threading.Thread(target=worker, name='worker-{}'.format(i), args=(pool,)).start()       

使用semaphore來完善代碼

import threading
import logging
import random

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

class Conn:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

class Pool:
    def __init__(self, count:int):
        self.count = count
        self.pool = [ self._connect('conn-{}'.format(x)) for x in range(self.count)]
        self.semahore = threading.Semaphore(count)

    def _connect(self, conn_name):
        return Conn(conn_name)

    def get_conn(self):
        self.semahore.acquire()
        conn = self.pool.pop()
        return conn

    def return_conn(self, conn:Conn):
        self.pool.append(conn)
        self.semahore.release()

pool = Pool(3)

def worker(pool:Pool):
    conn = pool.get_conn()
    logging.info(conn)
    threading.Event().wait(random.randint(1,4))
    pool.return_conn(conn)

for i in range(6):
    threading.Thread(target=worker, name='worker-{}'.format(i), args=(pool,)).start()

關于信號量release超出初始值范圍的問題

當我們使用semaphore的時候,如果還未acquire,就release了,會產生什么問題?
會產生是的信號量的值+1,超出了原本設置semaphore的初始值,下面的例子說明了這個問題

import threading
import logging

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

sema = threading.Semaphore(3)
logging.warning(sema.__dict__)
for _ in range(3):
    sema.acquire()

logging.warning('-----')
logging.warning(sema.__dict__)

for _ in range(4):
    sema.release()
logging.warning(sema.__dict__)

for _ in range(3):
    sema.acquire()
logging.warning('--------')
logging.warning(sema.__dict__)
sema.acquire()
logging.warning('======')
logging.warning(sema.__dict__)

所以這個這樣的問題,可以使用BoundedSemaphore類來實現有界的信號量,若relase超出了初始值的范圍,會拋出ValueError異常

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

隆子县| 兰西县| 彭山县| 东辽县| 常熟市| 桦南县| 玛沁县| 荥经县| 依安县| 金塔县| 固阳县| 岳阳县| 桑日县| 呼和浩特市| 颍上县| 白沙| 延吉市| 景泰县| 土默特右旗| 崇仁县| 万山特区| 琼结县| 扶风县| 新平| 白银市| 阿克陶县| 连山| 岳普湖县| 秦安县| 洛隆县| 新化县| 尤溪县| 云林县| 荥阳市| 琼中| 金门县| 边坝县| 瓦房店市| 清新县| 壶关县| 苍山县|