本文整理汇总了Python中thread.allocate_lock函数的典型用法代码示例。如果您正苦于以下问题:Python allocate_lock函数的具体用法?Python allocate_lock怎么用?Python allocate_lock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了allocate_lock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: demoWithLock
def demoWithLock():
import time
import thread
def loop0(lock):
print 'start loop0 at:', time.ctime()
time.sleep(4)
print 'loop0 done at:', time.ctime()
lock.release()
def loop1(lock):
print 'start loop1 at:', time.ctime()
time.sleep(2)
print 'loop1 done at:', time.ctime()
lock.release()
lock0 = thread.allocate_lock()
lock0.acquire()
lock1 = thread.allocate_lock()
lock1.acquire()
thread.start_new_thread(loop0, (lock0,))
thread.start_new_thread(loop1, (lock1,))
while lock0.locked(): pass
while lock1.locked(): pass
print 'all DONE at:', time.ctime()
示例2: test_current_frames
def test_current_frames(self):
import sys
import time
import thread
# XXX workaround for now: to prevent deadlocks, call
# sys._current_frames() once before starting threads.
# This is an issue in non-translated versions only.
sys._current_frames()
thread_id = thread.get_ident()
def other_thread():
print "thread started"
lock2.release()
lock1.acquire()
lock1 = thread.allocate_lock()
lock2 = thread.allocate_lock()
lock1.acquire()
lock2.acquire()
thread.start_new_thread(other_thread, ())
def f():
lock2.acquire()
return sys._current_frames()
frames = f()
lock1.release()
thisframe = frames.pop(thread_id)
assert thisframe.f_code.co_name in ('f', '?')
assert len(frames) == 1
_, other_frame = frames.popitem()
assert other_frame.f_code.co_name in ('other_thread', '?')
示例3: __init__
def __init__(self, world, name, center, width = 35, height = 45, beacon_point = Point(0, 0)):
# For simple bounding circle computations let the radius be half diagonal
WorldObject.__init__(self, center, sqrt(width**2 + height**2)/2)
self.wr = width/2
self.hr = height/2
self.world = world
self.name = name
self.beacon_point = beacon_point
# "Forward" is the unit direction vector where the robot is facing
# (0, 1) is the "default" (height along the Y axis)
self.forward = Point(0, 1)
self.left = Point(-self.forward.y, self.forward.x)
# Those are state parameters
self.leftSpeed = 0
self.rightSpeed = 0
# Camera sensor parameters
self.CAMERA_DEPTH = 120
self.CAMERA_SIDE = 100
# Write concurrency lock (we assume reads are atomic, and even if not, just ignore read errors)
self.data_lock = thread.allocate_lock()
# Whether there's a ball in the grabber
self.grabbed_ball = None
self.grabbed_ball_lock = thread.allocate_lock()
示例4: __init__
def __init__(self, title='', server=None, handle=0, parent=None):
if not server:
if parent:
server = parent.server
else:
server = Server.Server()
if handle or not self._type:
Widget.Widget.__init__(self, server, handle, parent)
else:
Widget.Widget.__init__(self, server, server.register(title, self._type), parent)
self.default_relationship = 'inside'
if parent is None:
self._widget_registry = {self.handle: self}
self._event_registry = EventRegistry()
self._event_stack = []
self._infilter_registry = {}
if thread is not None:
self._run_lock = thread.allocate_lock()
self._dispatch_lock = thread.allocate_lock()
self.app = self
else:
parent._notify_new_widget(self)
self._widget_registry = parent._widget_registry
self._event_registry = parent._event_registry
self._event_stack = parent._event_stack
self._infilter_registry = parent._infilter_registry
if thread is not None:
self._run_lock = parent._run_lock
self._dispatch_lock = parent._dispatch_lock
self.app = parent.app
示例5: __init__
def __init__(self, maxsize):
import thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire_lock()
self.fsema = thread.allocate_lock()
示例6: launch
def launch(samplingLogPattern, samplingBSQ):
global gnutellaPOP, crawlingQueue, crawlingQueueLock, peerActiveInGnu, peerQueuedInGnu
global mainLock, queue
samplingLogInit(samplingLogPattern)
mainLock = thread.allocate_lock()
queue = Queue.PriorityQueue()
p2pProtocol = './gnutella_%s' % platform.system().lower()
pop = Popen(['nice', 'bash', '-c', 'cd %s; ulimit -n hard; %s' % (os.path.dirname(p2pProtocol), \
p2pProtocol)], stdin = PIPE, stdout=PIPE, stderr=STDOUT, preexec_fn=os.setsid)
fin = pop.stdin
fout = pop.stdout
comm_server.sample_pop = gnutellaPOP = pop
crawlingQueueLock = thread.allocate_lock()
crawlingQueue = set()
peerActiveInGnu = 0
peerQueuedInGnu = 0
thread.start_new_thread(sampler_safety_wrapper, (writer, fin))
thread.start_new_thread(sampler_safety_wrapper, (reader, fout))
try:
samplingLoop(samplingBSQ)
finally:
samplingLogClose()
gc.collect()
示例7: __init__
def __init__(self):
self.blockCounter = 0
self.objCounter = 0
if (
"cache_meta_driver"
and "cache_storage_driver"
and "cache_block_size"
and "cache_meta_size" not in options.keys()
):
define("cache_meta_driver", default="mem", help="Metadata Driver")
define("cache_storage_driver", default="disk", help="Block Storage system")
define("cache_block_size", default=100, help="Cache Block Max size")
define("cache_meta_size", default=100, help="Cache Block Max size")
storage_plugin = "restfsc.cache.%s.CacheStorageDriver" % options.cache_storage_driver
storage_mod = __import__(storage_plugin, globals(), locals(), ["CacheStorageDriver"])
CacheStorageDriver = getattr(storage_mod, "CacheStorageDriver")
self.cacheStorageDriver = CacheStorageDriver()
meta_plugin = "restfsc.cache.%s.CacheMetaDriver" % options.cache_meta_driver
meta_mod = __import__(meta_plugin, globals(), locals(), ["CacheMetaDriver"])
CacheMetaDriver = getattr(meta_mod, "CacheMetaDriver")
self.cacheMetaDriver = CacheMetaDriver()
self.meta_lock = thread.allocate_lock()
self.block_lock = thread.allocate_lock()
#####STATS
self.num_get = 0
self.num_set = 0
self.num_get_failed = 0
示例8: __init__
def __init__(self, cfg):
BotBase.__init__(self, cfg)
self.type = 'irc'
self.wait = Wait()
self.outputlock = thread.allocate_lock()
self.fsock = None
self.oldsock = None
self.sock = None
self.nolimiter = self.cfg['nolimiter']
self.reconnectcount = 0
self.pongcheck = 0
self.nickchanged = 0
self.noauto433 = 0
if not self.state.has_key('alternick'):
self.state['alternick'] = self.cfg['alternick']
if not self.state.has_key('no-op'):
self.state['no-op'] = []
self.nick = self.cfg['nick']
self.nrevents = 0
self.gcevents = 0
self.outqueues = [Queue.Queue() for i in range(10)]
self.tickqueue = Queue.Queue()
self.nicks401 = []
self.stopreadloop = False
self.stopoutloop = False
if self.port == 0:
self.port = 6667
self.connectlock = thread.allocate_lock()
self.encoding = 'utf-8'
示例9: __init__
def __init__(self,init_path):
self.path = os.path.realpath(init_path)
self.AK = '72UZoe-AJao4469EfG0kSZ1B4CBzmn_WO6wd2fdQ'
self.SK = 'Bn6vHxfwuX5IKiruRJsBLNQCmJwzLWr_9CCN89-2'
self.BN = 'xiaoyphoto'
self.BD = '7xpg1h.com1.z0.glb.clouddn.com'
self.wait_time = 3600
self.pre = ''
self.user = ''
self.passwd = ''
self.inflock = thread.allocate_lock()
self.ordlock = thread.allocate_lock()
self.datlock = thread.allocate_lock()
self.lislock = thread.allocate_lock()
self.order = []
self.log_state = 0
self.filelist = []
self.clouds = []
self.static_file = '..\\map\\log.txt'
self.inf = dict()
self.__connect()
thread.start_new_thread(self.__run,())
示例10: __init__
def __init__(self, config):
self.config = config
self.MyHost = ''
self.ListenPort = self.config['GENERAL']['LISTEN_PORT']
self.sigLock = thread.allocate_lock() # For locking in the sigHandler
self.monLock = thread.allocate_lock() # For keeping the monitor thread sane
self.watchUpstream = 0
if not self.config['NTLM_AUTH']['NTLM_TO_BASIC']:
if not self.config['NTLM_AUTH']['PASSWORD']:
tries = 3
print '------------------------'
while tries and (not self.config['NTLM_AUTH']['PASSWORD']):
tries = tries - 1
self.config['NTLM_AUTH']['PASSWORD'] = getpass.getpass('Your NT password to be used:')
if not self.config['NTLM_AUTH']['PASSWORD']:
print 'Sorry. PASSWORD is required, bye.'
sys.exit(1)
else:
# TODO: migrate this properly so placeholders aren't required
self.config['NTLM_AUTH']['USER'] = 'placeholder_username'
self.config['NTLM_AUTH']['PASSWORD'] = 'placeholder_password'
# hashed passwords calculation
if self.config['DEBUG']['DEBUG']:
print ("user:%s") % self.config['NTLM_AUTH']['USER']
print ("passwd:%s") % self.config['NTLM_AUTH']['PASSWORD']
self.config['NTLM_AUTH']['LM_HASHED_PW'] = ntlm_procs.create_LM_hashed_password(self.config['NTLM_AUTH']['PASSWORD'])
self.config['NTLM_AUTH']['NT_HASHED_PW'] = ntlm_procs.create_NT_hashed_password(self.config['NTLM_AUTH']['PASSWORD'])
示例11: test_threadstate
def test_threadstate(self):
def thread_proc(start, loop, success, finished):
try:
try:
start.release()
x = 1
while not loop.locked():
x = -x
except StopIteration:
success.acquire()
finally:
finished.release()
start = allocate_lock()
start.acquire()
loop = allocate_lock()
success = allocate_lock()
finished = allocate_lock()
finished.acquire()
tid = start_new_thread(thread_proc, (start, loop, success, finished))
start.acquire()
rval = PyThreadState_SetAsyncExc(tid, StopIteration())
if rval > 1:
PyThreadState_SetAsyncExc(tid, py_object())
self.fail()
self.failUnlessEqual(rval, 1)
loop.acquire()
finished.acquire()
self.failUnless(success.locked())
示例12: write
def write(self, data="", flush=0):
import thread
if flush or len(self._data)>self._maxsize:
try:
lock = thread.allocate_lock()
lock.acquire(1)
fd = open(self._path, "ab+")
fd.write(self._data + data)
self._data = ""
fd.close()
if lock.locked():
lock.release()
return True
except:
try:
fd.close()
except:
pass
try:
if lock.locked():
lock.release()
except:
pass
return False
else:
try:
lock = thread.allocate_lock()
lock.acquire(1)
self._data += data
if lock.locked():
lock.release()
return True
except:
return False
示例13: __init__
def __init__(self, base_dir = '../InputData/GreekGear/GreekGearProductImages',
image_output_dirname='../OutputData/GreekGear/GreekGearWebsiteImages',
no_of_threads = 10,
get_image_size_only = 0,
NoOfRetries=0,
output_file_to_write_image_sizes = None,
writer = None,
log_file_sucess_obj = None,
log_file_fail_obj = None
):
if output_file_to_write_image_sizes == None:
output_file_to_write_image_sizes = image_output_dirname + '/' + str(time.time()).replace('.','') + 'image-size.csv'
global dirname
self.base_dir = base_dir;
#fname = 'greekgear_images.txt' #File name which stores various URL's
dirname = image_output_dirname # '../OutputData/GreekGear/GreekGearWebsiteImages' #Name of the directory to be created, to store the downloaded images
#crosswalk = 'greekgear_images.txt' #Crosswalk file to track the updated id
self.MAXTHREADS = no_of_threads # 10 #Max number of threads to be created
self.NoOfRetries = NoOfRetries
self.get_image_size_only = get_image_size_only
if writer == None:
self.output_file = output_file_to_write_image_sizes #"".join(["../OutputData/GreekGear/",'GreekGear.com-images-size.csv'])
self.final_csv_file = open(self.output_file, "wb") # binary mode to not add extra line breaks between rows in windows
self.writer = csv.writer(self.final_csv_file)
self.cw_lookup = dict()
self.writelock = thread.allocate_lock()
self.exitlock = [thread.allocate_lock() for i in range(self.MAXTHREADS)]
self.f_open_sucess = log_file_sucess_obj #open(log_file_sucess, 'w')
self.f_open_fail = log_file_fail_obj #open(log_file_fail, 'w')
示例14: dl
def dl(self):
lock1 = thread.allocate_lock()
flag1 = thread.allocate_lock()
flag2 = thread.allocate_lock()
songinfo = ''
picpath = ''
while True:
if len(self.songs)>2 or lock1.locked():
#print "self.song:",len(self.songs)
#print "lock1.locked():",lock1.locked()
sleep(1)
else:
if flag1.locked() and songinfo != '':
if flag2.locked():
songinfo['picture']=picpath
self.songs.append(songinfo)
print "new song"
songinfo = self.playlist.next()
musicname = songinfo['url'].split("/")[-1]
picname = songinfo['picture'].split("/")[-1]
picpath = TEMP_PATH+picname
savepath = TEMP_PATH+musicname
lock1.acquire()
if flag1.locked():
flag1.release()
if flag2.locked():
flag2.release()
flag1.acquire()
flag2.acquire()
print songinfo['picture']
thread.start_new_thread(download.download,(lock1,flag1,songinfo['url'],savepath,flag2,songinfo['picture'],picpath))
songinfo['path']=savepath
示例15: run
def run(self, argv):
# The real thing starts here
# FIXME: Maybe this should be done on __init__?
self.config = configlib.ConfigAgent()
self.config.parseCmdLine(sys.argv[1:]) # We need some config data before..
self.config.parseConfigFile()
# But we also need to give priority to parseCmdLine so it's parsed again...
self.config.parseCmdLine(sys.argv[1:])
self.logAgent = logger.LogAgent()
self.loadReplyList()
self.checkLock()
self.createLock()
# Prevent the list growing too much
if len(self.repliedList) > 500:
for i in xrange(len(self.repliedList) - 500):
del self.repliedList[0]
# Set the timeout
# FIXME: Duplicated in configlib.py!!!
if self.config.alarmtime != 0:
# 60 by default
setDefaultSocketTimeout(self.config.alarmtime)
self.CLock = thread.allocate_lock()
self.repLock = thread.allocate_lock()
# Main thread will create per-server threads
self.mainThread = threading.Thread(target=self.main)
self.mainThread.start()
return 0