• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python thread.allocate_lock函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中thread.allocate_lock函数的典型用法代码示例。如果您正苦于以下问题:Python allocate_lock函数的具体用法?Python allocate_lock怎么用?Python allocate_lock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了allocate_lock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()  
开发者ID:WenyuChang,项目名称:PythonDeepUsage,代码行数:26,代码来源:module_thread.py


示例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', '?')
开发者ID:yuyichao,项目名称:pypy,代码行数:33,代码来源:test_sysmodule.py


示例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()
开发者ID:AhtiL,项目名称:RobotexSimulator2011,代码行数:29,代码来源:robot.py


示例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
开发者ID:UIKit0,项目名称:picogui,代码行数:30,代码来源:Application.py


示例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()
开发者ID:asottile,项目名称:ancient-pythons,代码行数:7,代码来源:queue.py


示例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()
开发者ID:mingchen-chung,项目名称:JobSeeking,代码行数:25,代码来源:sample.py


示例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
开发者ID:fege,项目名称:Thesis-Project,代码行数:32,代码来源:CacheManager.py


示例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'
开发者ID:RetroRodent,项目名称:my-gozerbot,代码行数:29,代码来源:irc.py


示例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,())
开发者ID:sunluchang,项目名称:xiaoyPhoto,代码行数:31,代码来源:WebConnection.py


示例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'])
开发者ID:wuzhenda,项目名称:ntlmaps,代码行数:27,代码来源:server.py


示例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())
开发者ID:chmod007,项目名称:ctypeslib,代码行数:28,代码来源:test_pythonhdr.py


示例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
开发者ID:adroullier,项目名称:nive,代码行数:34,代码来源:utils.py


示例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')
开发者ID:beekal,项目名称:WebInfoScraper,代码行数:31,代码来源:cl_ImageDownloader.py


示例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
开发者ID:JiangYulin,项目名称:doubanFM,代码行数:32,代码来源:DLManager.py


示例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
开发者ID:juanjux,项目名称:animail,代码行数:32,代码来源:AnimailMain.py


示例16: newConnection

 def newConnection(self):
     '''create a new connection'''
     connectionPossibilities = self._connectionPossibilities[:]
     if not connectionPossibilities:
         return 
     l = thread.allocate_lock()
     l2 = thread.allocate_lock()
     def notify():
         released = False
         for p in connectionPossibilities[1:]:
             self.debug('released:', released)
             if not released and self.hasConnections():
                 self.debug('release')
                 l.release()
                 released = True
             yield
         if not released: l.release()
         yield
     generator = notify()
     def notify():
         with l2:
             next(generator)
     l.acquire(False)
     for possibility in connectionPossibilities:
         thread.start_new(self._connect, (possibility, notify))
     l.acquire()
     self.debug('hasconnection!!!')
开发者ID:isabelmette,项目名称:pynet,代码行数:27,代码来源:Process.py


示例17: record

def record(v, info, filename, audiofilename, \
	               mono, grey, greybits, monotreshold, fields):
	import thread
	format, x, y, number, rate = info
	fps = 59.64 # Fields per second
	# XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!)
	tpf = 1000.0 / fps # Time per field in msec
	#
	# Go grab
	#
	if audiofilename:
		gl.wintitle('(start audio) ' + filename)
		audiodone = thread.allocate_lock()
		audiodone.acquire_lock()
		audiostart = thread.allocate_lock()
		audiostart.acquire_lock()
		audiostop = []
		initaudio(audiofilename, audiostop, audiostart, audiodone)
		audiostart.acquire_lock()
	gl.wintitle('(rec) ' + filename)
	try:
		ninfo, data, bitvec = v.CaptureBurst(info)
	except sv.error, arg:
		print 'CaptureBurst failed:', arg
		print 'info:', info
		gl.wintitle(filename)
		return
开发者ID:asottile,项目名称:ancient-pythons,代码行数:27,代码来源:Vrecb.py


示例18: test_dealloc_other_thread

def test_dealloc_other_thread():
    if not thread:
        py.test.skip("this is a test about thread")
    seen = []
    someref = []
    lock = thread.allocate_lock()
    lock.acquire()
    lock2 = thread.allocate_lock()
    lock2.acquire()
    def f():
        g1 = greenlet(fmain)
        g1.switch(seen)
        someref.append(g1)
        del g1
        gc.collect()
        lock.release()
        lock2.acquire()
        greenlet()   # trigger release
        lock.release()
        lock2.acquire()
    t = threading.Thread(target=f)
    t.start()
    lock.acquire()
    assert seen == []
    assert len(someref) == 1
    del someref[:]
    gc.collect()
    # g1 is not released immediately because it's from another thread
    assert seen == []
    lock2.release()
    lock.acquire()
    assert seen == [greenlet.GreenletExit]
    lock2.release()
    t.join()
开发者ID:mickg10,项目名称:DARLAB,代码行数:34,代码来源:test_greenlet.py


示例19: __init__

    def __init__(self, agent, p2p=False):  # , msgrecv):
        self._client = agent.getAID().getName()
        #self.msgrecv = msgrecv
        self.myAgent = agent
        self._server = agent.server

        # Add Disco Behaviour
        agent.addBehaviour(DiscoBehaviour(), Behaviour.MessageTemplate(Iq(queryNS=NS_DISCO_INFO)))

        # Add Stream Initiation Behaviour
        iqsi = Iq()
        si = iqsi.addChild("si")
        si.setNamespace(NS_SI) #"http://jabber.org/protocol/si")
        agent.addBehaviour(StreamInitiationBehaviour(), Behaviour.MessageTemplate(iqsi))

        # Add P2P Behaviour
        self.p2p_ready = False  # Actually ready for P2P communication
        self.p2p = p2p
        self.p2p_routes = {}
        self.p2p_lock = thread.allocate_lock()
        self.p2p_send_lock = thread.allocate_lock()
        self._p2p_failures = 0  # Counter for failed attempts to send p2p messages
        if p2p:
            agent.registerLogComponent("p2p")
            self.P2PPORT = random.randint(70000, 80000)  # Random P2P port number
            p2pb = P2PBehaviour()
            agent.addBehaviour(p2pb)
开发者ID:Aharobot,项目名称:spade,代码行数:27,代码来源:peer2peer.py


示例20: __init__

	def __init__(self):
		Thread.__init__(self)
		self.too_old_clockssecs = 1000 * 30   # 30 seconds

		self.midiin_lock = thread.allocate_lock()
		self.scheduled_lock = thread.allocate_lock()
		self.midiin = {}
		self.midiin_add = None
		self.midiin_del = None
		self.midiout_del = None
		self.midiout = {}

		self.firstevent = 0
		self.nextevent = 0
		self.keepgoing = True
		self.clocks_per_second = 192.0   # 96/quarter, 120 bpm
		self.timenow = Midi.time_now()
		self.scheduled = []
		self.next_scheduled = None
		self.callback_func = None
		self.callback_data = None
		self.outputcallback_func = None
		self.outputcallback_data = None
		
		self._timer_calls = []
		self._next_timer = None
开发者ID:nosuchtim,项目名称:MMTT1,代码行数:26,代码来源:midiutil.py



注:本文中的thread.allocate_lock函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python thread.exit函数代码示例发布时间:2022-05-27
下一篇:
Python thread.allocate函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap