2015-11-20 21:57:28 +01:00
|
|
|
#
|
|
|
|
# This file is part of pysnmp software.
|
|
|
|
#
|
2017-01-12 01:05:56 +01:00
|
|
|
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
|
2015-11-20 21:57:28 +01:00
|
|
|
# License: http://pysnmp.sf.net/license.html
|
|
|
|
#
|
2011-02-11 22:38:19 +01:00
|
|
|
import random
|
|
|
|
|
|
|
|
random.seed()
|
2008-04-27 23:46:04 +02:00
|
|
|
|
2016-04-01 23:06:11 +02:00
|
|
|
|
2016-06-12 14:07:24 +02:00
|
|
|
class Integer(object):
|
2015-11-20 21:57:28 +01:00
|
|
|
"""Return a next value in a reasonably MT-safe manner"""
|
2016-04-01 23:06:11 +02:00
|
|
|
|
2008-04-27 23:46:04 +02:00
|
|
|
def __init__(self, maximum, increment=256):
|
|
|
|
self.__maximum = maximum
|
|
|
|
if increment >= maximum:
|
|
|
|
increment = maximum
|
|
|
|
self.__increment = increment
|
2016-04-01 23:06:11 +02:00
|
|
|
self.__threshold = increment // 2
|
2011-02-11 22:38:19 +01:00
|
|
|
e = random.randrange(self.__maximum - self.__increment)
|
2016-04-01 23:06:11 +02:00
|
|
|
self.__bank = list(range(e, e + self.__increment))
|
2008-04-27 23:46:04 +02:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '%s(%d, %d)' % (
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.__maximum,
|
|
|
|
self.__increment
|
2016-04-01 23:06:11 +02:00
|
|
|
)
|
2015-10-17 11:54:53 +02:00
|
|
|
|
2008-04-27 23:46:04 +02:00
|
|
|
def __call__(self):
|
|
|
|
v = self.__bank.pop(0)
|
|
|
|
if v % self.__threshold:
|
|
|
|
return v
|
|
|
|
else:
|
|
|
|
# this is MT-safe unless too many (~ increment/2) threads
|
|
|
|
# bump into this code simultaneously
|
2016-04-01 23:06:11 +02:00
|
|
|
e = self.__bank[-1] + 1
|
2008-04-27 23:46:04 +02:00
|
|
|
if e > self.__maximum:
|
|
|
|
e = 0
|
2016-04-01 23:06:11 +02:00
|
|
|
self.__bank.extend(range(e, e + self.__threshold))
|
2008-04-28 09:59:46 +02:00
|
|
|
return v
|