def _run_in_multiple_threads(test1):
test1()
import sys
try:
import thread
except ImportError:
import _thread as thread
errors = []
def wrapper(lock):
try:
test1()
except:
errors.append(sys.exc_info())
lock.release()
locks = []
for i in range(10):
_lock = thread.allocate_lock()
_lock.acquire()
thread.start_new_thread(wrapper, (_lock,))
locks.append(_lock)
for _lock in locks:
_lock.acquire()
if errors:
raise errors[0][1]
python类allocate_lock()的实例源码
def __init__(self, port="/dev/ttyUSB0", baudrate=57600, timeout=0.5):
self.PID_RATE = 30 # Do not change this! It is a fixed property of the Arduino PID controller.
self.PID_INTERVAL = 1000 / 30
self.port = port
self.baudrate = baudrate
self.timeout = timeout
self.encoder_count = 0
self.writeTimeout = timeout
self.interCharTimeout = timeout / 30.
# Keep things thread safe
self.mutex = thread.allocate_lock()
# An array to cache analog sensor readings
self.analog_sensor_cache = [None] * self.N_ANALOG_PORTS
# An array to cache digital sensor readings
self.digital_sensor_cache = [None] * self.N_DIGITAL_PORTS
def __init__(self, name, cache_size=512, marshal=marshal):
"""
Create a persistent FIFO queue named by the 'name' argument.
The number of cached queue items at the head and tail of the queue
is determined by the optional 'cache_size' parameter. By default
the marshal module is used to (de)serialize queue items, but you
may specify an alternative serialize module/instance with the
optional 'marshal' argument (e.g. pickle).
"""
assert cache_size > 0, 'Cache size must be larger than 0'
self.name = name
self.cache_size = cache_size
self.marshal = marshal
self.index_file = os.path.join(name, INDEX_FILENAME)
self.temp_file = os.path.join(name, 'tempfile')
self.mutex = thread.allocate_lock()
self._init_index()
def __init__(self, maxEntries=10000, maxAge=14400):
"""Create a new SessionCache.
@type maxEntries: int
@param maxEntries: The maximum size of the cache. When this
limit is reached, the oldest sessions will be deleted as
necessary to make room for new ones. The default is 10000.
@type maxAge: int
@param maxAge: The number of seconds before a session expires
from the cache. The default is 14400 (i.e. 4 hours)."""
self.lock = thread.allocate_lock()
# Maps sessionIDs to sessions
self.entriesDict = {}
#Circular list of (sessionID, timestamp) pairs
self.entriesList = [(None,None)] * maxEntries
self.firstIndex = 0
self.lastIndex = 0
self.maxAge = maxAge
def _run_in_multiple_threads(test1):
test1()
import sys
try:
import thread
except ImportError:
import _thread as thread
errors = []
def wrapper(lock):
try:
test1()
except:
errors.append(sys.exc_info())
lock.release()
locks = []
for i in range(10):
_lock = thread.allocate_lock()
_lock.acquire()
thread.start_new_thread(wrapper, (_lock,))
locks.append(_lock)
for _lock in locks:
_lock.acquire()
if errors:
raise errors[0][1]
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def test_thread_separation():
def f():
c = PluginManager()
lock1.acquire()
lock2.acquire()
c.x = 7
lock1.release()
lock2.release()
lock1 = thread.allocate_lock()
lock2 = thread.allocate_lock()
lock1.acquire()
thread.start_new_thread(f, ())
a = PluginManager()
a.x = 5
lock1.release()
lock2.acquire()
return a.x
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def test_thread_separation():
def f():
c = PluginManager()
lock1.acquire()
lock2.acquire()
c.x = 7
lock1.release()
lock2.release()
lock1 = thread.allocate_lock()
lock2 = thread.allocate_lock()
lock1.acquire()
thread.start_new_thread(f, ())
a = PluginManager()
a.x = 5
lock1.release()
lock2.acquire()
return a.x
def __init__(self, lock=None):
# the lock actually used by .acquire() and .release()
if lock is None:
self.mutex = thread.allocate_lock()
else:
if hasattr(lock, 'acquire') and \
hasattr(lock, 'release'):
self.mutex = lock
else:
raise TypeError, 'condition constructor requires ' \
'a lock argument'
# lock used to block threads until a signal
self.checkout = thread.allocate_lock()
self.checkout.acquire()
# internal critical-section lock, & the data it protects
self.idlock = thread.allocate_lock()
self.id = 0
self.waiting = 0 # num waiters subject to current release
self.pending = 0 # num waiters awaiting next signal
self.torelease = 0 # num waiters to release
self.releasing = 0 # 1 iff release is in progress
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def __init__(self):
self.debugApplication = None
self.debuggingThread = None
self.debuggingThreadStateHandle = None
self.stackSnifferCookie = self.stackSniffer = None
self.codeContainerProvider = None
self.debuggingThread = None
self.breakFlags = None
self.breakReason = None
self.appDebugger = None
self.appEventConnection = None
self.logicalbotframe = None # Anything at this level or below does not exist!
self.currentframe = None # The frame we are currently in.
self.recursiveData = [] # Data saved for each reentery on this thread.
bdb.Bdb.__init__(self)
self._threadprotectlock = thread.allocate_lock()
self.reset()
SessionCache.py 文件源码
项目:plugin.video.streamondemand-pureita
作者: orione7
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def __init__(self, maxEntries=10000, maxAge=14400):
"""Create a new SessionCache.
@type maxEntries: int
@param maxEntries: The maximum size of the cache. When this
limit is reached, the oldest sessions will be deleted as
necessary to make room for new ones. The default is 10000.
@type maxAge: int
@param maxAge: The number of seconds before a session expires
from the cache. The default is 14400 (i.e. 4 hours)."""
self.lock = thread.allocate_lock()
# Maps sessionIDs to sessions
self.entriesDict = {}
#Circular list of (sessionID, timestamp) pairs
self.entriesList = [(None,None)] * maxEntries
self.firstIndex = 0
self.lastIndex = 0
self.maxAge = maxAge
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def test_thread_separation():
def f():
c = PluginManager()
lock1.acquire()
lock2.acquire()
c.x = 7
lock1.release()
lock2.release()
lock1 = thread.allocate_lock()
lock2 = thread.allocate_lock()
lock1.acquire()
thread.start_new_thread(f, ())
a = PluginManager()
a.x = 5
lock1.release()
lock2.acquire()
return a.x
def __init__(self, maxEntries=10000, maxAge=14400):
"""Create a new SessionCache.
@type maxEntries: int
@param maxEntries: The maximum size of the cache. When this
limit is reached, the oldest sessions will be deleted as
necessary to make room for new ones. The default is 10000.
@type maxAge: int
@param maxAge: The number of seconds before a session expires
from the cache. The default is 14400 (i.e. 4 hours)."""
self.lock = thread.allocate_lock()
# Maps sessionIDs to sessions
self.entriesDict = {}
#Circular list of (sessionID, timestamp) pairs
self.entriesList = [(None,None)] * maxEntries
self.firstIndex = 0
self.lastIndex = 0
self.maxAge = maxAge
def main(url):
global db,cursor
try:
db=pymysql.connect('localhost','root','root','test')
cursor=db.cursor()
sqlDelete='delete from portsscan'
cursor.execute(sqlDelete)
db.commit()
except Exception,e:
print '1',e
# try:
# os.remove('./../../result/allPorts.txt')
# except Exception,e:
# print e
# url = raw_input('Input the ip you want to scan:\n')
lock = thread.allocate_lock()
ip_scan(url)
db.close()
return
def main():
print 'starting threads...'
locks = []
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock)
for i in nloops:
thread.start_new_thread(loop,
(i, loops[i], locks[i]))
for i in nloops:
while locks[i].locked(): pass
print 'all DONE at:', ctime()
def __init__(self, dsn, dsnDict, console):
"""
Object constructor.
:param dsn: The database connection string.
:param dsnDict: The database connection string parsed into a dict.
:param console: The console instance.
"""
self.dsn = dsn
self.dsnDict = dsnDict
self.console = console
self.db = None
self._lock = thread.allocate_lock()
####################################################################################################################
# #
# CONNECTION INITIALIZATION/TERMINATION/RETRIEVAL #
# #
####################################################################################################################
def __init__(self, n=1):
sync = thread.allocate_lock()
self._acquire = sync.acquire
self._release = sync.release
pool = []
self._lists = (
pool, # Collection of locks representing threads are not
# waiting for work to do
[], # Request queue
[], # Pool of locks representing threads that are
# waiting (ready) for work to do.
)
self._acquire() # callers will block
try:
while n > 0:
l = thread.allocate_lock()
l.acquire()
pool.append(l)
thread.start_new_thread(ZServerPublisher,
(self.accept,))
n = n - 1
finally:
self._release() # let callers through now
def __init__(self, application, environ=None,
multithreaded=True, **kw):
"""
environ, if present, must be a dictionary-like object. Its
contents will be copied into application's environ. Useful
for passing application-specific variables.
Set multithreaded to False if your application is not MT-safe.
"""
if kw.has_key('handler'):
del kw['handler'] # Doesn't make sense to let this through
super(WSGIServer, self).__init__(**kw)
if environ is None:
environ = {}
self.application = application
self.environ = environ
self.multithreaded = multithreaded
# Used to force single-threadedness
self._app_lock = thread.allocate_lock()
def test_thread_separation():
def f():
c = PluginManager()
lock1.acquire()
lock2.acquire()
c.x = 7
lock1.release()
lock2.release()
lock1 = thread.allocate_lock()
lock2 = thread.allocate_lock()
lock1.acquire()
thread.start_new_thread(f, ())
a = PluginManager()
a.x = 5
lock1.release()
lock2.acquire()
return a.x
def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
"""Create a new buffered reader using the given readable raw IO object.
"""
if not raw.readable():
raise IOError('"raw" argument must be readable.')
_BufferedIOMixin.__init__(self, raw)
if buffer_size <= 0:
raise ValueError("invalid buffer size")
self.buffer_size = buffer_size
self._reset_read_buf()
self._read_lock = Lock()
def __init__(self, raw,
buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
if not raw.writable():
raise IOError('"raw" argument must be writable.')
_BufferedIOMixin.__init__(self, raw)
if buffer_size <= 0:
raise ValueError("invalid buffer size")
if max_buffer_size is not None:
warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
self._warning_stack_offset)
self.buffer_size = buffer_size
self._write_buf = bytearray()
self._write_lock = Lock()
def allocate_lock():
"""Dummy implementation of thread.allocate_lock()."""
return LockType()
def __init__(self, bind, connect):
'Initialize the Proxy object.'
self.__bind = bind
self.__connect = connect
self.__status = False
self.__thread = False
self.__lock = _thread.allocate_lock()
def __init__(self, function, *args, **kwargs):
'Initialize the Mille_Timer object.'
self.__function = function
self.__args = args
self.__kwargs = kwargs
self.__status = False
self.__thread = False
self.__lock = _thread.allocate_lock()
def __init__(self, socket):
'Initialize the Zero SPOTS Protocol object.'
self.__sock = socket
self.__send = _thread.allocate_lock()
self.__recv = _thread.allocate_lock()
self.__temp = ''