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


Python Condition.release方法代码示例

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


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

示例1: stepwise_scheduler

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class stepwise_scheduler(Thread):
    def __init__(self, event_table):
        Thread.__init__(self)
        self.__turn_counter = 0
        self.condition = Condition()
        self.semaphore = Semaphore()
        self.semaphore.acquire()
        self.event = None
        self.event_table = event_table

    def get_current_turn(self):
        self.__turn_counter

    def set_event(self, event):
        self.event = event

    def run(self):
        while True:
            self.__turn_counter += 1
            self.condition.acquire()
            if self.event == None:
                self.condition.wait()
            event = self.event
            self.event = None
            checked = False
            for event_entry in self.event_table:
                if isinstance(event, event_entry[0]):
                    event_entry[1].call(event)
                    checked = True
                    break
                if not checked:
                    print_warning("No suitable handler for" + str(event) + " in entry table")

            self.condition.release()
开发者ID:vedun-z,项目名称:ggrl,代码行数:36,代码来源:stepwise_scheduler.py

示例2: MessageQueue

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class MessageQueue(object):
    """The message queue used internally by Gossip."""

    def __init__(self):
        self._queue = deque()
        self._condition = Condition()

    def pop(self):
        self._condition.acquire()
        try:
            while len(self._queue) < 1:
                self._condition.wait()
            return self._queue.pop()
        finally:
            self._condition.release()

    def __len__(self):
        return len(self._queue)

    def __deepcopy__(self, memo):
        newmq = MessageQueue()
        newmq._queue = copy.deepcopy(self._queue, memo)
        return newmq

    def appendleft(self, msg):
        self._condition.acquire()
        try:
            self._queue.appendleft(msg)
            self._condition.notify()
        finally:
            self._condition.release()
开发者ID:yy860179277,项目名称:sawtooth-core,代码行数:33,代码来源:gossip_core.py

示例3: process_sequence

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
    def process_sequence(self, sequence):
        """
        @param sequence: the movement sequence to execute
        @return: dictionary of sensor readings
        """
        self.log.debug('process sequence')
        # parse the json message
        jseq = json.loads(sequence)
        moveseq = jseq['sequence']

        for moves in moveseq:
            self.log.debug('processing move %s' % moves)
            condition = Condition()
            thread_count = 0
            for move in moves:
                thread_count += 1
                servo_instruction = self.process_move(move)
                move_servo_thread = ServoThread(servo_instruction, self.pwm_queue, condition, thread_count, self.update_current_pulse)
                move_servo_thread.setDaemon(False)
                move_servo_thread.setName('Servo %d' % servo_instruction['channel'])
                move_servo_thread.start()
            condition.acquire()
            if thread_count > 0:
                condition.wait()
            # wait for all threads to finish before doing next loop
            condition.release()
开发者ID:margic,项目名称:pihex,代码行数:28,代码来源:controller.py

示例4: SharedCell

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class SharedCell(object):
    """Shared data for the producer/consumer problem."""
    
    def __init__(self):
        self._data = -1
        self._writeable = True
        self._condition = Condition()

    def setData(self, data):
        """Producer's method to write to shared data."""
        self._condition.acquire()
        while not self._writeable:
            self._condition.wait()
        print "%s setting data to %d" % \
              (currentThread().getName(), data)
        self._data = data
        self._writeable = False
        self._condition.notify()
        self._condition.release()

    def getData(self):
        """Consumer's method to read from shared data."""
        self._condition.acquire()
        while self._writeable:
            self._condition.wait()
        print "%s accessing data %d" % \
              (currentThread().getName(), self._data)
        self._writeable = True
        self._condition.notify()
        self._condition.release()
        return self._data
开发者ID:gregpuzzles1,项目名称:Sandbox,代码行数:33,代码来源:pc2.py

示例5: External_command

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class External_command(object):
    work_available = None
    work = None

    def __init__(self, command, max_workers = _MAX_WORKERS):
        self.work_available = Condition()
        self.work = []
        for i in range(0, max_workers):
            _Worker(command, self)

    def process_command(self, data, result_callback, *callback_parameters):
        wi = Work_item(tuple(data), result_callback, callback_parameters)
        self.work_available.acquire()
        self.work.append(wi)
        self.work_available.notify()
        self.work_available.release()
        return wi

    def shutdown(self):
        self.work_available.acquire()
        self.work.append(None)
        self.work_available.notify()
        self.work_available.release()

    def process_result(self, result_callback, result, *callback_parameters):
        try:
            result_callback(result, *callback_parameters)
        except Exception as ex:
            if isinstance(ex, SystemExit):
                raise
            dump_exception('External_command: unhandled exception in external command results callback')
开发者ID:sippy,项目名称:b2bua,代码行数:33,代码来源:External_command.py

示例6: NotificationQueue

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class NotificationQueue(Queue):
    """ A queue class that notifies waiting threads when the queue is available for
    reading."""
    def __init__(self):
        """ Constructor."""
        Queue.__init__(self)
        self.lock = Condition()

    def get(self):
        """ Get an item from the queue. This method is thread-safe.
        Method must be called on a non-empty queue.
        Return : the first item from the queue
        Raises: a EmptyQueue exeception
        """
        return Queue.get(self, False)

    def put(self, item):
        """ Add a new item to the queue. This method is thread-safe.
        Threads that are waiting for get an item are notified.
        item: new item to add to the queue.
        Return : None
        """
        self.lock.acquire()
        Queue.put(self, item)
        self.lock.notify()
        self.lock.release()

    def acquire(self):
        self.lock.acquire()

    def release(self):
        self.lock.release()

    def wait(self):
        self.lock.wait()
开发者ID:BackupTheBerlios,项目名称:solipsis-svn,代码行数:37,代码来源:container.py

示例7: LockedDirectories

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class LockedDirectories(object):
    """
    Class that keeps a list of locked directories
    """
    def __init__(self):
        self.dirs = set()
        self.cv = Condition()

    def run_in(self, dir_):
        """
        Start running in the directory and lock it
        """
        self.cv.acquire()
        while dir_ in self.dirs:
            self.cv.wait()
        self.dirs.add(dir_)
        self.cv.release()

    def done(self, dir_):
        """
        Finished with the directory, unlock it
        """
        self.cv.acquire()
        self.dirs.remove(dir_)
        self.cv.notify_all()
        self.cv.release()
开发者ID:gcovr,项目名称:gcovr,代码行数:28,代码来源:workers.py

示例8: GridGenerationUpdateThread

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class GridGenerationUpdateThread(Thread):
    disconnect = False
    elecgen    = None
    sleeper    = None
    def __init__(self, parent):
        Thread.__init__(self)
        self.disconnect = False
        self.elecgen = parent
        self.ngdata  = ElectricityGenerationDataSource()
        self.sleeper = Condition()
    def stopUpdates(self):
        self.disconnect = True
        self.sleeper.acquire()
        self.sleeper.notify()
        self.sleeper.release()
    def run(self):
        while self.disconnect == False:
            emxml = self.ngdata.DownloadRealtimeXML()
            try: 
                self.elecgen.energyMix = self.ngdata.ParseRealtimeXML(emxml)
            except Exception, exc:
                trc.Error("failed to parse realtime xml")
                trc.Error(str(emxml))
                trc.Error(repr(exc))
                trc.Error(repr(exc.message))
            # go to sleep for a while - the realtime data doesn't update very
            #  often, so no need to download it constantly!
            self.sleeper.acquire()
            self.sleeper.wait(180)
            self.sleeper.release()
开发者ID:jmhdz,项目名称:currentcostgui,代码行数:32,代码来源:electricitygeneration.py

示例9: test_call_self

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
    def test_call_self(self):
        m = Mock()
        cond = Condition()
        self._recv_call_id = None

        def event_cb(_, evt):
            if evt.type == EventType.call_invite:
                m()
                self._recv_call_id = evt.request.call_id
            # condition of event callback returning
            cond.acquire()
            cond.notify()
            cond.release()

        self.ctx.event_callback = event_cb
        # start call:
        # build and send invitation message
        cond.acquire()
        with self.ctx.lock:
            msg = call.InitInvite(
                self.ctx,
                to_url='sip:{0[0]}:{0[1]}'.format(self.listen_address),
                from_url='sip:{0[0]}:{0[1]}'.format(self.listen_address),
            )
            send_call_id = msg.call_id
            self.ctx.call_send_init_invite(msg)
        # wait event result!
        cond.wait(1)
        cond.release()
        # assertion
        self.assertEqual(m.call_count, 1)
        self.assertEqual(self._recv_call_id, send_call_id)
开发者ID:tanbro,项目名称:exosip2ctypes,代码行数:34,代码来源:test_call.py

示例10: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class Barrier:
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.count = num_threads
        self.iter = 0
        self.cond = Condition()

    def wait(self):
        self.cond.acquire()
        i = self.iter
        self.count -= 1
        if self.count == 0:
            self.iter += 1
            self.count = self.num_threads
            self.cond.notify_all()
            self.cond.release()
            return True
        # Release lock and block this thread until notified/woken.
        # Allow for spurious wake-ups.
        while 1:
            self.cond.wait(None)
            if i != self.iter:
                break
        self.cond.release()
        return False
开发者ID:OxfordSKA,项目名称:OSKAR,代码行数:27,代码来源:barrier.py

示例11: SafeLoopArray

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class SafeLoopArray(object):
	def __init__(self , data, lengh = 10):
		self._lengh = lengh
		self._data	= []
		self._index = 0;
		self._lock  = Condition(Lock())

		for i in range(lengh):
			self._data.append(data)
			

	def add(self , data):
		self._lock.acquire()
		try:
			i = self._index%self._lengh
			#print "self._lengh = {0},self._index={1},i={2}".format(self._lengh,self._index, i)
			self._data[i] = data
			self._index = self._index+1
		finally:
			self._lock.release()

	def get(self , pos):
		if (pos >= self._lengh):
			print("out of range")
			return None
		self._lock.acquire()
		try:
			return self._data[pos]
		finally:
			self._lock.release()
开发者ID:Adam57,项目名称:Crawler,代码行数:32,代码来源:safe_loop_array.py

示例12: SimpleRemoteCall

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class SimpleRemoteCall(object):
    returncode = None
    returned = False
    
    def signal(self):
        self.cond.acquire()
        self.returned = True
        self.cond.notify()
        self.cond.release()
        
    def errorHandler(self, error):
        self.returncode = error
        self.signal()
        
    def successHandler(self, object):
        self.returncode = object
        self.signal()
        
    def __call__(*arg, **kwargs):
        pass
        
    def __init__(self, remoteReference, *arg, **kwargs):
        self.cond = Condition()
        deref = remoteReference.callRemote(*arg, **kwargs)
        deref.addCallbacks(self.successHandler, self.errorHandler)
        
    def wait(self, timeout = None):
        self.cond.acquire()
        if not self.returned:
            self.cond.wait(timeout)
            
        self.cond.release()
        if not self.returned:
            raise TimeExpired('timeout')
开发者ID:snua12,项目名称:zlomekfs,代码行数:36,代码来源:remoteZfs.py

示例13: MWPixelClock

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class MWPixelClock(object):
    def __init__(self, conduitName):
        self.conduit = Conduit(conduitName)
        self.conduit.initialize()
        self.conduit.register_local_event_code(0,'#stimDisplayUpdate')
        self.conduit.register_callback_for_name('#stimDisplayUpdate', self.receive_event)
        self.codes = []
        self.cond = Condition()
        self.maxCodes = 100
    
    def receive_event(self, event):
        for s in event.data:
            if s is None:
                continue
            if s.has_key('bit_code'):
                self.cond.acquire()
                self.codes.append((s['bit_code'],event.time/1000000.))
                # if len(self.codes) > 2:
                #     #logging.debug('MW bit_code = %i' % s['bit_code'])
                #     #print s['bit_code']
                #     #logging.debug("MW Delta: %s" % delta_code(self.codes[-1][0], self.codes[-2][0]))
                while len(self.codes) > self.maxCodes:
                    self.codes.pop(0)
                self.cond.notifyAll()
                self.cond.release()
开发者ID:coxlab,项目名称:pixel-clock-audio-unit,代码行数:27,代码来源:test_sync.py

示例14: TimeTrigger

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class TimeTrigger(Thread):
    """Wait for a given time.
    """

    def __init__(self, time):
        Thread.__init__(self)
        self.time = time
        self.loop = True
        self.cond = Condition()
        # self.start()
        self.exit_status = 0

    def run(self):
        while self.loop and self.time > datetime.utcnow():
            self.cond.acquire()
            now = datetime.utcnow()
            diff = (self.time - now).seconds + (self.time - now).microseconds / 1000000.0
            self.cond.wait(diff)
            self.cond.release()

    def cancel(self):
        self.loop = False
        self.exit_status = 1
        self.cond.acquire()
        self.cond.notify()
        self.cond.release()

    def __repr__(self):
        return "Time trigger " + str(self.time)
开发者ID:pytroll,项目名称:pytroll,代码行数:31,代码来源:tm.py

示例15: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import release [as 别名]
class ConnectorPool:
  """ A thread-safe connection pool. 

  TODO: Make this an actual queue, not a stack. Nomenclature is imporant
  sometimes. 
  """
  
  def __init__(self, Connector, count=20, user=None, password=None, db=None):
    self.pool = [ Connector(user, password, db) for _ in range(count) ]
    self.C_pool = Condition()
      
  def dequeue(self):
    """ Get connector. 
    
    :rtype: seaice.SeaIceConnector.SeaIceConnector
    """
    self.C_pool.acquire()
    while len(self.pool) == 0: 
      self.C_pool.wait()
    db_con = self.pool.pop()
    self.C_pool.release()
    return db_con

  def enqueue(self, db_con): 
    """ Release connector.

    :param db_con: The connector. 
    :type db_con: seaice.SeaIceConnector.SeaIceConnector
    """
    self.C_pool.acquire()
    self.pool.append(db_con)
    self.C_pool.notify()
    self.C_pool.release()
开发者ID:lnielsen,项目名称:yamz,代码行数:35,代码来源:ConnectorPool.py


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