Last active
December 23, 2015 00:09
-
-
Save tianweidut/6551406 to your computer and use it in GitHub Desktop.
safe call function in period
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: utf-8 | |
import threading | |
import time | |
MAX = 8 | |
MIN = 0 | |
TIME_LIMIT = 60 | |
g = 0 | |
mutex = threading.Lock() | |
start = time.time() | |
def incr(): | |
mutex.acquire() | |
now = time.time() | |
if now - start > TIME_LIMIT: | |
g = 0 | |
flag = True | |
start = now | |
else: | |
if g < MAX: | |
g = g + 1 | |
flag = True | |
else: | |
flag False | |
mutex.release() | |
return flag | |
def decr(): | |
mutex.acquire() | |
g = max(0, g-1) | |
mutex.release() | |
def safe_call(*args, **kwags): | |
if incr(): | |
result = call(*args, **kwargs) | |
decr() | |
else: | |
result = None | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment