博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 采用 BoundedSemaphore 限制多进程访问qps
阅读量:6869 次
发布时间:2019-06-26

本文共 1293 字,大约阅读时间需要 4 分钟。

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
42
43
44
45
46
47
48
49
50
51
52
53
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 00:06:12 2017
 
@author: 37652
"""
 
import 
threading
import 
time
import 
timer2
import 
requests
 
def 
showfun(n):
    
requests.get(
"http://test.com/"
)
    
print 
"here\n"
 
     
def 
release():
    
print 
"%s begin start release =============== \n" 
%
(time.ctime())
    
# 增加之前 先清除之前遗留的 避免出现遗留计数器影响下一秒qps
    
while 
semlock.acquire(blocking
=
0
):
            
pass
        
# 增加计数器
    
for 
in 
range
(
20
):
        
try
:
            
semlock.release()
        
except 
Exception, e:
                
# 出现异常 进行推出 理想状态是出现计数器自增超过配额
                
# TODO 未对异常进行细分 
            
print 
"\n======"
,e
            
break
    
print 
"%s end start release =============== \n" 
%
(time.ctime())
 
if 
__name__ 
=
= 
'__main__'
:
    
maxconnections 
= 
20   
# 计数器最大值
    
semlock 
= 
threading.BoundedSemaphore(maxconnections)
     
    
reThread 
= 
timer2.apply_interval(
1000
, release) 
# 每秒钟进行一次计数器释放
     
    
list
=
[]
    
= 
0
    
while 
True
:
        
semlock.acquire()
        
i
+
=
1
        
t
=
threading.Thread(target
=
showfun, args
=
(i,))
        
list
.append(t)
        
t.start()
        
if 
time.time() > 
1505754200
:   
# 测试结束时间戳
            
break
         
    
for 
in 
list
:
        
j.join()
    
reThread.cancel()

注: python threading 模块内 有两个计数器 同步原语

    Semaphore                    无上限

    BoundedSemaphore     初始设置最大值 如果release调用超过最大值则出ValueError

本文转自  拖鞋崽  51CTO博客,原文链接:http://blog.51cto.com/1992mrwang/1966522

转载地址:http://hccfl.baihongyu.com/

你可能感兴趣的文章
SymmetricDS: 数据库数据同步Database synchronization
查看>>
Disabling OOM killer on Ubuntu 14.04
查看>>
VBS备份脚本
查看>>
CentOS 6.5 自动安装镜像
查看>>
Storm与Spark Streaming比较
查看>>
我的友情链接
查看>>
Exchange Server 运维管理01:Exchange中Active Directory 有什么用?
查看>>
dhcp服务在企业中的应用
查看>>
linux系统管理之四:服务状态
查看>>
VMware View FAQ[一]
查看>>
【原创翻译】布尔值(boolean)
查看>>
三元运算式、lambda表达式、内置函数map、reduce、filter以及yield生成器
查看>>
MySQL分库分表分表后数据的查询(5th)
查看>>
iOS-点击图片放大,再次点击返回原视图 类似查看相册的功能
查看>>
JAVA -- stateless4j StateMachine 使用浅析(二)
查看>>
oracle checkpoint
查看>>
KVM虚拟化开源高可用方案(六)ISCSI ON DRBD搭建及常见故障处理
查看>>
android device related
查看>>
iOS 6 Beta3即将发布,iPhone面板谍照已经曝光
查看>>
hadoop 源码包编译
查看>>