更新时间:2022-10-03 22:04:10
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 i 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 = []
i = 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 j in list :
j.join()
reThread.cancel()
|
注: python threading 模块内 有两个计数器 同步原语
Semaphore 无上限
BoundedSemaphore 初始设置最大值 如果release调用超过最大值则出ValueError
本文转自 拖鞋崽 51CTO博客,原文链接:http://blog.51cto.com/1992mrwang/1966522