当前位置: 首页>>代码示例>>Python>>正文


Python Lock.release方法代码示例

本文整理汇总了Python中threading.Lock.release方法的典型用法代码示例。如果您正苦于以下问题:Python Lock.release方法的具体用法?Python Lock.release怎么用?Python Lock.release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Lock的用法示例。


在下文中一共展示了Lock.release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: DataWindow

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class DataWindow(Thread):
    def __init__(self,data_adapter):
        Thread.__init__(self)
        self.win = N.zeros((100,3))
        self.winlock = Lock()
        self.data_adapter = data_adapter
    
    def run(self):
        self.data_adapter.start()
        self.running = True
        while self.running:
            self.winlock.acquire()
            try:
                while 1:
                    newdata = self.data_adapter.q.get(block=False)
                    self.win[:-1,:] = self.win[1:,:]
                    self.win[-1,:] = newdata[1:]
            except Queue.Empty:
                pass
            finally:
                self.winlock.release()
        self.data_adapter.stop()
    
    def stop(self):
        self.running = False
开发者ID:NickFoubert,项目名称:adxl-visualize,代码行数:27,代码来源:viz.py

示例2: _CoreScheduleThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class _CoreScheduleThread(Thread):
    def __init__(self,threadpool):
        self.scheduletasks = [];
        self.tasklock = Lock();
        self.condition = Condition(Lock())
        self.threadpool = threadpool
        Thread.__init__(self)

    def run(self):
        while True:
            self.condition.acquire()
            if len(self.scheduletasks) == 0:
                self.condition.wait();
            else:
                task = self.scheduletasks.pop(0)
                if dates.current_timestamps()>=task.nexttime: 
                    self.threadpool.execute(task.function,*task.args,**task.kwargs)
                    task.nexttime = dates.current_timestamps()+task.period;
                else:
                    self.condition.wait(task.nexttime-dates.current_timestamps())
                self.addtask(task)
            self.condition.release()

    
    def addtask(self,task): # copy on write
        self.tasklock.acquire()
        tasks = [ t for t in self.scheduletasks ]
        tasks.append(task)
        tasks.sort(key=lambda task:task.nexttime)
        self.scheduletasks = tasks
        self.tasklock.release()
开发者ID:IMISME,项目名称:yuntao.py,代码行数:33,代码来源:executors.py

示例3: WorkerTask

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class WorkerTask(object):
    """
    This class used to represent page loading task
    """
    def __init__(self, args, routine, user_data = None):
        self._lock_complete = Lock()
        self.__complete = False
        self.gathered = False
        self.args = args
        if callable(routine):
            self.routine = routine
        else:
            raise AttributeError('<routine> argument should be callable function')
        self.user_data = user_data
        self.result = []
        self.thread = None

    def _get_complete(self):
        """complete property getter"""
        self._lock_complete.acquire()
        complete = self.__complete
        self._lock_complete.release()
        return complete

    def _set_complete(self, state):
        """complete property setter"""
        if type(state) != types.BooleanType:
            raise TypeError('state should be boolean')
        self._lock_complete.acquire()
        self.__complete = state
        self._lock_complete.release()

    complete = property(_get_complete, _set_complete)
开发者ID:ktisha,项目名称:ebook-service,代码行数:35,代码来源:WorkerTask.py

示例4: WaitCursor

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class WaitCursor(Thread):
    """A waiting cursor for long operation that
    catch output and flush it after waiting"""
    def __init__(self):
        self.state = "WAIT"
        self.lock = Lock()           # Lock used to synchronise IO and cursor stop
        Thread.__init__(self)

    def run(self):
        """Method executed when the thread object start() method is called"""

        realStdout = sys.stdout # Backup stdout
        tmpStdout = StringIO()  # Store here all data output during waiting state
        sys.stdout = tmpStdout  # Capture stdout
        cursorState = ("-", "\\", "|", "/")
        i = 0
        self.lock.acquire()
        while self.state == "WAIT":
            realStdout.write(cursorState[i % 4])
            realStdout.flush()
            sleep(0.1)
            realStdout.write("\b")
            i += 1

        # Restore standard output and print temp data
        sys.stdout = realStdout
        sys.stdout.write(tmpStdout.getvalue())
        sys.stdout.flush()
        self.lock.release()

    def stop(self):
        self.state = "STOP"
        self.lock.acquire() # Wait end of IO flush before returning
开发者ID:sdelcros,项目名称:pysql,代码行数:35,代码来源:pysqlhelpers.py

示例5: handle

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
	def handle(self):
		#try:
			data, socket = self.request

			lock = Lock()
			lock.acquire()

			DataOffset    = struct.unpack('<H',data[139:141])[0]
			BrowserPacket = data[82+DataOffset:]
			ReqType       = RequestType(BrowserPacket[0])

			Domain = Decode_Name(data[49:81])
			Name   = Decode_Name(data[15:47])
			Role1  = NBT_NS_Role(data[45:48])
			Role2  = NBT_NS_Role(data[79:82])
			Fprint = WorkstationFingerPrint(data[190:192])
			Roles  = ParseRoles(data[192:196])

			print text("[BROWSER] Request Type : %s" % ReqType)
			print text("[BROWSER] Address      : %s" % self.client_address[0])
			print text("[BROWSER] Domain       : %s" % Domain)
			print text("[BROWSER] Name         : %s" % Name)
			print text("[BROWSER] Main Role    : %s" % Role1)
			print text("[BROWSER] 2nd Role     : %s" % Role2)
			print text("[BROWSER] Fingerprint  : %s" % Fprint)
			print text("[BROWSER] Role List    : %s" % Roles)

			RAPThisDomain(self.client_address[0], Domain)

			lock.release()
开发者ID:0xicl33n,项目名称:Potato,代码行数:32,代码来源:BrowserListener.py

示例6: start_manager

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
    def start_manager(self):

        exit_flags[self.tab_id] = 0

        log.info('START | Layers Download Manager')

        thread_list = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet']
        queue_lock = Lock()
        work_queue = Queue.Queue(len(self.file_paths_and_sizes))
        threads = []

        for thread_name in thread_list:
            key = str(uuid.uuid4())
            thread = LayerDownloadThread(self.source, thread_name, work_queue, queue_lock, key, self.target_dir, self.tab_id)
            thread.start()
            if not threads_map_key in thread_manager_processes:
                thread_manager_processes[threads_map_key] = {}
            thread_manager_processes[threads_map_key][key] = thread
            threads.append(thread)

        queue_lock.acquire()
        for word in self.file_paths_and_sizes:
            work_queue.put(word)
        queue_lock.release()

        while not work_queue.empty():
            pass

        exit_flags[self.tab_id] = 1

        for t in threads:
            t.join()

        log.info('DONE | Layers Download Manager')
开发者ID:geobricks,项目名称:pgeo,代码行数:36,代码来源:download_threads_manager.py

示例7: InMemoryItemValue

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class InMemoryItemValue(object):
  _lock = None
  """:type _lock Lock"""

  def __init__(self, value=None, expire_in=None):
    self._lock = Lock()
    self._value = value
    self._expire_in = None
    self._expire_in_time = None

    self.update_expire_time(expire_in)

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, val):
    self._lock.acquire()
    self._value = val
    self._expire_in = datetime.now() + timedelta(seconds=float(self._expire_in_time)) if self._expire_in_time else None
    self._lock.release()

  def update_expire_time(self, t):
    self._expire_in_time = t

  @property
  def is_expired(self):
    return (self._expire_in - datetime.now()).days < 0 if self._expire_in else False
开发者ID:hapylestat,项目名称:appcore,代码行数:31,代码来源:in_memory.py

示例8: _setup_to_do_n_cycles

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
    def _setup_to_do_n_cycles(self, number_of_cycles: int, updates_each_cycle: UpdateCollection=None):
        """
        Sets up the test so that the retriever will only do n cycles.
        :param number_of_cycles: the number of cycles to do
        """
        if updates_each_cycle is None:
            updates_each_cycle = UpdateCollection([])

        semaphore = Semaphore(0)
        lock_until_counted = Lock()
        lock_until_counted.acquire()

        def increase_counter(*args) -> UpdateCollection:
            semaphore.release()
            lock_until_counted.acquire()
            return updates_each_cycle

        self.retrieval_manager.update_mapper.get_all_since.side_effect = increase_counter
        self.retrieval_manager.start()

        run_counter = 0
        while run_counter < number_of_cycles:
            semaphore.acquire()
            run_counter += 1
            lock_until_counted.release()
            if run_counter == number_of_cycles:
                self.retrieval_manager.stop()

        self.retrieval_manager.update_mapper.get_all_since.side_effect = None
开发者ID:wtsi-hgi,项目名称:cookie-monster,代码行数:31,代码来源:test_manager.py

示例9: IndependentWorker

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class IndependentWorker(Thread):
    def __init__(self, id, manager, workerArgs = None):
        '''A worker needs a task stack(queue), a name (id) and a boss (manager)'''
        self.id = id
        self.manager = manager
        self.completedTasksLock = Lock()
        self.completedTasks = 0
        Thread.__init__(self)
    def run(self):
        subject = self.manager.getTask()
        while subject != None:
            if self._task(subject):
                self.completedTasksLock.acquire()
                self.completedTasks += 1
                self.completedTasksLock.release()
            subject = self.manager.getTask()
        self._close()
        sys.exit()
    def getAndResetCompletedTasks(self):
        completedTasks = self.completedTasks
        self.completedTasksLock.acquire()
        self.completedTasks = 0
        self.completedTasksLock.release()
        return completedTasks
    def _task(self, subject):
        print 'You should initialize Worker._task(self, subject)'
        sys.exit()
        pass
    def _close(self):
        pass
开发者ID:nicholas-leonard,项目名称:equanimity,代码行数:32,代码来源:multi.py

示例10: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class Promise:
  def __init__(self):
    self.value = None
    self.mutex = Lock()
    self.callbacks = []

  def updateValue(self, new_value):
    if (self.mutex.acquire(blocking = False) and self.value is None):
      self.value = new_value
      for cb in self.callbacks:
        cb(new_value)
      self.mutex.release()
    else:
      raise RuntimeError("cannot set the value of an already resolved promise")

  def addCallback(self, cb):
    self.mutex.acquire(blocking = True)
    self.callbacks.append(cb)
    self.mutex.release()
    return self

  def map(self, f):
    fp = Promise()
    def chain(v):
      fp.updateValue(f(v))
    self.addCallback(chain)
    return fp

  def flatMap(self, f):
    fp = Promise()
    def chain(v):
      f(v).addCallback(fp.updateValue)
    self.addCallback(chain)
    return fp
开发者ID:entombedvirus,项目名称:GitGutter,代码行数:36,代码来源:promise.py

示例11: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class TUNERS:
    def __init__(self, str):
        from threading import Lock

        tuners = "".join(str.split()) # remove white space
        tuners = tuners.split(',')
        tuners = [tuple(x.split(':')[0:2]) for x in tuners]
        # Add priority
        self.tuner_list = [(i, v[0], v[1]) for i,v in enumerate(tuners)]
        heapq.heapify(self.tuner_list)
        self.lock = Lock()

    def get_tuner(self):
        self.lock.acquire()
        try:
            tuner = heapq.heappop(self.tuner_list)
        except IndexError:
            tuner = None
        finally:
            self.lock.release()
        return tuner

    def put_tuner(self, tuner):
        self.lock.acquire()
        heapq.heappush(self.tuner_list, tuner)
        self.lock.release()
开发者ID:astondg,项目名称:hdhomerun_recorder,代码行数:28,代码来源:recorder.py

示例12: PandoraPool

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class PandoraPool(object):
	def __init__(self, poolSize, proxy=None, expireTime=3600):
		self.size = poolSize
		self.proxy = proxy
		self.expire = expireTime
		self.pool = [self.createPandoraAgent() for i in xrange(self.size)]
		self.mutex = Lock()

	def createPandoraAgent(self):
		return PandoraAgent(datetime.now() + timedelta(0, self.expire), self.proxy)

	def refreshPandoraAgent(self, agent):
		if agent.isExpired():
			agent.authenticate_connection()
			agent.setExpireDate(datetime.now() + timedelta(0, self.expire))
		return agent

	def getAgent(self):
		try:
			return self.refreshPandoraAgent(self.pool.pop())
		except IndexError:
			return self.createPandoraAgent()

	def hasAvailableConnections(self):
		return len(self.pool) > 0

	def releaseAgent(self, agent):
		self.mutex.acquire()
		if len(self.pool) < self.size:
			self.pool.append(agent)
		self.mutex.release()
开发者ID:elElmo,项目名称:walkman,代码行数:33,代码来源:pandora_pool.py

示例13: TfBroadcasterThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class TfBroadcasterThread(Thread):
    def __init__(self,child_frame,parent_frame,tf_br=None):
        Thread.__init__(self)
        rospy.loginfo("Initializing tf broadcaster with child frame "+child_frame+" and parent frame "+parent_frame)
        if tf_br is None:
            self.tf_br = tf.TransformBroadcaster()
        else:
            self.tf_br = tf_br
        self.translation = None
        self.quaternion = None
        self.child_frame = child_frame
        self.parent_frame = parent_frame
        self.has_transformation=False
        self.lock=Lock()
            
    def set_transformation(self,translation,quaternion):
        self.lock.acquire()
        self.translation = translation
        self.quaternion = quaternion
        self.lock.release()
        self.has_transformation =True

    def run(self):
        while not rospy.is_shutdown():
            try:
                if self.has_transformation:
                    self.lock.acquire()
                    self.tf_br.sendTransform(self.translation ,self.quaternion , rospy.Time.now(), self.child_frame,self.parent_frame)
                    self.lock.release()
            except Exception,e:
                print 'TfBroadcasterThread:',e
开发者ID:kuka-isir,项目名称:depth_cam_extrinsics_calib,代码行数:33,代码来源:compute_transform_6d.py

示例14: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class DebuggingLock:
    def __init__(self, name):
        self.lock = Lock()
        self.name = name

    def acquire(self, blocking = 1):
        self.print_tb("Acquire lock")
        self.lock.acquire(blocking)
        self.logmsg("===== %s: Thread %s acquired lock\n"%
            (self.name, currentThread().getName()))

    def release(self):
        self.print_tb("Release lock")
        self.lock.release()

    def logmsg(self, msg):
        loglock.acquire()
        logfile.write(msg + "\n")
        logfile.flush()
        loglock.release()

    def print_tb(self, msg):
        self.logmsg(".... %s: Thread %s attempting to %s\n"% \
                    (self.name, currentThread().getName(), msg) + \
                    "\n".join(traceback.format_list(traceback.extract_stack())))
开发者ID:Deepanshu2017,项目名称:offlineimap,代码行数:27,代码来源:debuglock.py

示例15: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import release [as 别名]
class Manager:
  def __init__(self):
    self.networks = set()
    self.logs = []
    self.next_log_id = 0
    self.log_lock = Lock()

  def notifyNetUp(self, pno, net_name):
    self.networks.add(net_name)
    sys.stdout.write(">> network: %s is up (%d)\n" % (net_name, len(self.networks)))

  def getNetworks(self):
    return self.networks

  def getLogs(self, since=-1):
    if since >= 0:
      return filter(lambda l: l['id'] > since, self.logs)
    else:
      return self.logs

  def putLog(self, host, log):
    self.log_lock.acquire()
    l = {'id': self.next_log_id, 'host': host, 'log': log}
    self.next_log_id = self.next_log_id + 1
    sys.stdout.write(">> log: %s\n" % json.dumps(l))
    self.logs.append(l)
    self.log_lock.release()
开发者ID:itszero,项目名称:onenet,代码行数:29,代码来源:manager.py


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