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


猜你喜欢

转载自blog.51cto.com/14531342/2462907