python 線程信號量semaphore(33)

通過前面對 線程互斥鎖lock /  線程事件event / 線程條件變量condition / 線程定時器timer 的講解,相信你對線程threading模塊已經有了一定的瞭解,同時執行多個線程的確可以提高程序的效率,但是並非線程的數量越多越好,可能對於計算機而言,你直接運行20~30線程可能沒太大影響,如果同時運行上千個甚至上萬個呢?我相信你電腦會直接癱瘓……

 

耳朵

 

一.semaphore信號量原理

多線程同時運行,能提高程序的運行效率,但是並非線程越多越好,而semaphore信號量可以通過內置計數器來控制同時運行線程的數量,啓動線程(消耗信號量)內置計數器會自動減一,線程結束(釋放信號量)內置計數器會自動加一;內置計數器爲零,啓動線程會阻塞,直到有本線程結束或者其他線程結束爲止;

 

喲呵

 

二.semaphore信號量相關函數介紹

acquire() — 消耗信號量,內置計數器減一;

release() — 釋放信號量,內置計數器加一;

在semaphore信號量有一個內置計數器,控制線程的數量,acquire()會消耗信號量,計數器會自動減一;release()會釋放信號量,計數器會自動加一;當計數器爲零時,acquire()調用被阻塞,直到release()釋放信號量爲止。

python學習

 

三.semaphore信號量使用

創建多個線程,限制同一時間最多運行5個線程,示例代碼如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

# !usr/bin/env python

# -*- coding:utf-8 _*-

"""

@Author:何以解憂

@Blog(個人博客地址): shuopython.com

@WeChat Official Account(微信公衆號):猿說python

@Github:www.github.com

 

@File:python_semaphore.py

@Time:2019/10/23 21:25

 

@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!

"""

 

# 導入線程模塊

import threading

# 導入時間模塊

import time

 

# 添加一個計數器,最大併發線程數量5(最多同時運行5個線程)

semaphore = threading.Semaphore(5)

 

def foo():

    semaphore.acquire()    #計數器獲得鎖

    time.sleep(2)   #程序休眠2秒

    print("當前時間:",time.ctime()) # 打印當前系統時間

    semaphore.release()    #計數器釋放鎖

 

 

if __name__ == "__main__":

 

    thread_list= list()

    for i in range(20):

        t=threading.Thread(target=foo,args=()) #創建線程

        thread_list.append(t)

        t.start()  #啓動線程

 

    for t in thread_list:

        t.join()

 

    print("程序結束!")

輸出結果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

當前時間: Wed Oct 23 22:21:59 2019

當前時間: Wed Oct 23 22:21:59 2019

當前時間: Wed Oct 23 22:21:59 2019

當前時間: Wed Oct 23 22:21:59 2019

當前時間: Wed Oct 23 22:21:59 2019

當前時間: Wed Oct 23 22:22:01 2019

當前時間: Wed Oct 23 22:22:01 2019

當前時間: Wed Oct 23 22:22:01 2019

當前時間: Wed Oct 23 22:22:01 2019

當前時間: Wed Oct 23 22:22:01 2019

當前時間: Wed Oct 23 22:22:03 2019

當前時間: Wed Oct 23 22:22:03 2019

當前時間: Wed Oct 23 22:22:03 2019

當前時間: Wed Oct 23 22:22:03 2019

當前時間: Wed Oct 23 22:22:03 2019

當前時間: Wed Oct 23 22:22:05 2019

當前時間: Wed Oct 23 22:22:05 2019

當前時間: Wed Oct 23 22:22:05 2019

當前時間: Wed Oct 23 22:22:05 2019

當前時間: Wed Oct 23 22:22:05 2019

程序結束!

根據打印的日誌可以看出,同一時間只有5個線程運行,間隔兩秒之後,再次啓動5個線程,直到20個線程全部運行結束爲止;如果沒有設置信號量Semapaore,創建線程直接start(),輸出的時間全部都是一樣的,這個問題比較簡單,可以自己去實驗一下!

 

python學習

 

猜你喜歡:

1.python線程的創建和參數傳遞

2.python字典推導式

3.python列表推導式

4.python return邏輯運算符

5.python 不定長參數*argc,**kargcs

 

轉載請註明猿說Python » python線程信號量semaphore


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章