Python threading.Condition() Examples

The following are 30 code examples of threading.Condition(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module threading , or try the search function .
Example #1
Source File: fig20_06.py    From PythonClassBook with GNU General Public License v3.0 8 votes vote down vote up
def __init__( self ):
      """Initialize variables and setup server"""
      
      HOST = ""
      PORT = 5000

      self.board = []
      self.currentPlayer = 0
      self.turnCondition = threading.Condition()
      self.gameBeginEvent = threading.Event()

      for i in range( 9 ):
         self.board.append( None )

      # setup server socket
      self.server = socket.socket( socket.AF_INET,
         socket.SOCK_STREAM )
      self.server.bind( ( HOST, PORT ) )
      self.display( "Server awaiting connections..." ) 
Example #2
Source File: Eaglepy.py    From PyEagle with GNU Lesser General Public License v2.1 8 votes vote down vote up
def executeCommand(self,cmdtype,args=[]):
        
        cmdid = str(uuid4().hex)
        
        self.commandQueueLock.acquire()
        self.commandCondition[cmdid] = [Condition(),None]
        self.commandQueue.append([cmdid,cmdtype,args])
        self.commandCondition[cmdid][0].acquire()
        self.commandQueueLock.release()
        
        self.commandCondition[cmdid][0].wait()

        condition = self.commandCondition[cmdid][0]
        result    = self.commandCondition[cmdid][1]
        
        condition.release()
        return result; 
Example #3
Source File: _notification.py    From python-zhmcclient with Apache License 2.0 7 votes vote down vote up
def __init__(self, handover_dict, handover_cond):
        """
        Parameters:

          handover_dict (dict): Dictionary for handing over the notification
            header and message from this listener thread to the receiver
            thread. Must initially be an empty dictionary.

          handover_cond (threading.Condition): Condition object for handing
            over the notification from this listener thread to the receiver
            thread. Must initially be a new threading.Condition object.
        """

        # Sync variables for thread-safe handover between listener thread and
        # receiver thread:
        self._handover_dict = handover_dict  # keys: headers, message
        self._handover_cond = handover_cond

        # Wait timeout to honor keyboard interrupts after this time:
        self._wait_timeout = 10.0  # seconds 
Example #4
Source File: requeue.py    From browserscope with Apache License 2.0 7 votes vote down vote up
def __init__(self,
               queue_capacity,
               requeue_capacity=None,
               queue_factory=Queue.Queue,
               get_time=time.time):
    """Initialize a ReQueue instance.

    Args:
      queue_capacity: The number of items that can be put in the ReQueue.
      requeue_capacity: The numer of items that can be reput in the ReQueue.
      queue_factory: Used for dependency injection.
      get_time: Used for dependency injection.
    """
    if requeue_capacity is None:
      requeue_capacity = queue_capacity

    self.get_time = get_time
    self.queue = queue_factory(queue_capacity)
    self.requeue = queue_factory(requeue_capacity)
    self.lock = threading.Lock()
    self.put_cond = threading.Condition(self.lock)
    self.get_cond = threading.Condition(self.lock) 
Example #5
Source File: circular_buffer.py    From resolwe with Apache License 2.0 7 votes vote down vote up
def __init__(
        self, buffer_size: int = DEFAULT_BUFFER_LENGTH, name: Optional[str] = None
    ):
        """Initialize circular buffer."""
        # + 1 since at least one element in the buffer must be empty
        self.__bs = buffer_size + 1
        # Construct a buffer
        self.__buffer = memoryview(bytearray(self.__bs))
        # Where to start reading from.
        self.__tail = 0
        # Where to start writing into.
        self.__head = 0
        self.__buffer_modify = Condition()
        # How many bytes user wants to read.
        self.__reading_bytes = 0
        # Is the stream closed.
        self.__closed = False
        self._bytes_read = 0
        self.name = name 
Example #6
Source File: queue.py    From jawfish with MIT License 6 votes vote down vote up
def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)

        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = threading.Lock()

        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = threading.Condition(self.mutex)

        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = threading.Condition(self.mutex)

        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = threading.Condition(self.mutex)
        self.unfinished_tasks = 0 
Example #7
Source File: tornado_fetcher.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def sync_fetch(self, task):
        '''Synchronization fetch, usually used in xmlrpc thread'''
        if not self._running:
            return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))

        wait_result = threading.Condition()
        _result = {}

        def callback(type, task, result):
            wait_result.acquire()
            _result['type'] = type
            _result['task'] = task
            _result['result'] = result
            wait_result.notify()
            wait_result.release()

        wait_result.acquire()
        self.ioloop.add_callback(self.fetch, task, callback)
        while 'result' not in _result:
            wait_result.wait()
        wait_result.release()
        return _result['result'] 
Example #8
Source File: expectations.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, stream_timeout=None, max_parallel_processing=1, **kwds):
        """
        :param scheduler: the decorated scheduler
        :param stream_timeout: the default timeout value in seconds used by StreamScheduler.join
        :param max_parallel_processing: the maximum number of parallelized expectation
            processing (defaults to 1)
        """
        queue_size = 1024
        self._attr.stream_scheduler = Namespace()
        self._attr.stream_scheduler.timeout = stream_timeout
        self._attr.stream_scheduler.max_parallel_processing = max_parallel_processing
        self._attr.stream_scheduler.token_count = threading.BoundedSemaphore(
            max_parallel_processing
        )
        self._attr.stream_scheduler.expectation_queue = deque([], queue_size)
        self._attr.stream_scheduler.pending_expectations = set()
        self._attr.stream_scheduler.on_done_condition = threading.Condition() 
Example #9
Source File: core.py    From westpa with MIT License 6 votes vote down vote up
def __init__(self, task_id=None):
        self.task_id = task_id or uuid.uuid4()

        self._condition = threading.Condition()
        self._done = False
        self._result = None
        self._exception = None
        self._traceback = None

        # a set of Events representing who is waiting on results from this future
        # this set will be cleared after the result is updated and watchers are notified        
        self._watchers = set()
        
        # a set of functions that will be called with this future as an argument when it is updated with a
        # result. This list will be cleared after the result is updated and all callbacks invoked
        self._update_callbacks = [] 
Example #10
Source File: Queue.py    From meddle with MIT License 6 votes vote down vote up
def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)
        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = _threading.Lock()
        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = _threading.Condition(self.mutex)
        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = _threading.Condition(self.mutex)
        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = _threading.Condition(self.mutex)
        self.unfinished_tasks = 0 
Example #11
Source File: Queue.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)
        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = _threading.Lock()
        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = _threading.Condition(self.mutex)
        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = _threading.Condition(self.mutex)
        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = _threading.Condition(self.mutex)
        self.unfinished_tasks = 0 
Example #12
Source File: synchronized.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def synchronized(f):
	done = Condition()
	f.in_progress = False

	def sync(*args, **kw):
		done.acquire()
		if not f.in_progress:
			f.in_progress = True
			done.release()
			try:
				return f(*args, **kw)
			finally:
				f.in_progress = False
				with done:
					done.notify_all()
		else:
			done.wait()
			assert(not f.in_progress)
			done.release()
	return sync 
Example #13
Source File: _device_listener.py    From myo-python with MIT License 6 votes vote down vote up
def __init__(self, device, timestamp, firmware_version, mac_address,
               condition_class=threading.Condition):
    self._device = device
    self._mac_address = mac_address
    self._cond = condition_class()
    self._pair_time = timestamp
    self._unpair_time = None
    self._connect_time = None
    self._disconnect_time = None
    self._emg = None
    self._orientation_update_index = 0
    self._orientation = Quaternion.identity()
    self._acceleration = Vector(0, 0, 0)
    self._gyroscope = Vector(0, 0, 0)
    self._pose = Pose.rest
    self._arm = None
    self._x_direction = None
    self._rssi = None
    self._battery_level = None
    self._firmware_version = firmware_version
    self._name = None 
Example #14
Source File: pubSub.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def run(self):
    while True:
      integer = random.randint(0,1000)
      self.condition.acquire()
      print("Condition Acquired by Publisher: {}".format(self.name))
      self.integers.append(integer)
      print("Publisher {} appending to array: {}".format(self.name, integer))
      self.condition.notify()
      print("Condition Released by Publisher: {}".format(self.name))
      self.condition.release()
      time.sleep(1) 
Example #15
Source File: pubSub.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def run(self):
    while True:
      self.condition.acquire()
      print("Condition Acquired by Consumer: {}".format(self.name))
      while True:
        if self.integers:
          integer = self.integers.pop()
          print("{} Popped from list by Consumer: {}".format(integer, self.name))
          break
        print("Condition Wait by {}".format(self.name))
        self.condition.wait()
      print("Consumer {} Releasing Condition".format(self.name))
      self.condition.release() 
Example #16
Source File: pubSub.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def main():
  integers = []
  condition = threading.Condition()
  
  # Our Publisher
  pub1 = Publisher(integers, condition)
  pub1.start()

  # Our Subscribers
  sub1 = Subscriber(integers, condition)
  sub2 = Subscriber(integers, condition)
  sub1.start()
  sub2.start()

  ## Joining our Threads
  pub1.join()
  consumer1.join()
  consumer2.join() 
Example #17
Source File: producerConsumer.py    From Learning-Concurrency-in-Python with MIT License 5 votes vote down vote up
def main():
    integers = []
    condition = threading.Condition()
    t1 = Producer(integers, condition)
    t2 = Consumer(integers, condition)
    t1.start()
    t2.start()
    t1.join()
    t2.join() 
Example #18
Source File: DNRelay.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, spath, sip_logger):
        if spath.startswith('unix:'):
            spath = spath[5:]
        self.spath = spath
        self.sip_logger = sip_logger
        self.wi_available = Condition()
        self.wi = []
        Thread.__init__(self)
        self.setDaemon(True)
        self.start() 
Example #19
Source File: CLIManager.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, clientsock, clim):
        #print(self.__init__)
        Thread.__init__(self)
        self.clientsock = clientsock
        self.clim = clim
        self.w_available = Condition()
        self.wbuffer = bytes()
        self.setDaemon(True)
        self.start() 
Example #20
Source File: Udp_server.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, global_config, uopts):
        self.uopts = uopts.getCopy()
        self.skt = socket.socket(self.uopts.family, socket.SOCK_DGRAM)
        if self.uopts.laddress != None:
            ai = socket.getaddrinfo(self.uopts.laddress[0], None, self.uopts.family)
            if self.uopts.family == socket.AF_INET:
                address = (ai[0][4][0], self.uopts.laddress[1])
            else:
                address = (ai[0][4][0], self.uopts.laddress[1], ai[0][4][2], ai[0][4][3])
            if (self.uopts.flags & socket.SO_REUSEADDR) != 0:
                self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if hasattr(socket, 'SO_REUSEPORT') and \
              (self.uopts.flags & socket.SO_REUSEPORT) != 0:
                self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            self.skt.bind(address)
            if self.uopts.laddress[1] == 0:
                self.uopts.laddress = self.skt.getsockname()
        self.sendqueue = []
        self.stats = [0, 0, 0]
        self.wi_available = Condition()
        self.wi = []
        self.asenders = []
        self.areceivers = []
        if self.uopts.nworkers == None:
            nworkers = _DEFAULT_NWORKERS
        else:
            nworkers = self.uopts.nworkers
        for i in range(0, nworkers):
            self.asenders.append(AsyncSender(self))
            self.areceivers.append(AsyncReceiver(self)) 
Example #21
Source File: Rtp_proxy_client_stream.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, global_config, address = '/var/run/rtpproxy.sock', \
      bind_address = None, nworkers = 1, family = socket.AF_UNIX):
        #print('Rtp_proxy_client_stream.__init__', address, bind_address, nworkers, family)
        if family == socket.AF_UNIX:
            self.is_local = True
            self.address = address
        else:
            self.is_local = False
            self.address = self.getdestbyaddr(address, family)
        self.family = family
        self.wi_available = Condition()
        self.wi = []
        self.nworkers = nworkers
        self.workers = []
        for i in range(0, self.nworkers):
            try:
                self.workers.append(_RTPPLWorker(self))
            except:
                break
        self.nworkers_act = i + 1
        self.delay_flt = recfilter(0.95, 0.25) 
Example #22
Source File: SipLogger.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, app, call_id = 'GLOBAL', logfile = '/var/log/sip.log'):
        self.itime = time()
        self.app = '/%s' % app
        self.call_id = call_id
        bend = os.environ.get('SIPLOG_BEND', 'stderr').lower()
        tform = os.environ.get('SIPLOG_TFORM', 'abs').lower()
        if tform == 'rel':
            self.offstime = True
            itime = os.environ.get('SIPLOG_TSTART', self.itime)
            self.itime = float(itime)
        self.level = eval('SIPLOG_' + os.environ.get('SIPLOG_LVL', 'INFO'))
        if bend == 'stderr':
            self.write = self.write_stderr
        elif bend == 'none':
            self.write = self.donoting
        else:
            self.write = self.write_logfile
            self.wi_available = Condition()
            self.wi = []
            if bend != 'syslog':
                self.logger = AsyncLogger(app, self)
                self.logfile = os.environ.get('SIPLOG_LOGFILE_FILE', logfile)
                self.signal_handler = LogSignal(self, SIGUSR1, self.reopen)
            else:
                self.logger = AsyncLoggerSyslog(app, self)
                self.app = '' 
Example #23
Source File: comm.py    From overhaul-distillation with MIT License 5 votes vote down vote up
def __init__(self):
        self._result = None
        self._lock = threading.Lock()
        self._cond = threading.Condition(self._lock) 
Example #24
Source File: queue.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)
        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = _threading.Lock()
        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = _threading.Condition(self.mutex)
        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = _threading.Condition(self.mutex)
        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = _threading.Condition(self.mutex)
        self.unfinished_tasks = 0 
Example #25
Source File: pool.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, cache):
        self._cond = threading.Condition(threading.Lock())
        self._job = next(job_counter)
        self._cache = cache
        self._items = collections.deque()
        self._index = 0
        self._length = None
        self._unsorted = {}
        cache[self._job] = self 
Example #26
Source File: utils.py    From lnd_grpc with MIT License 5 votes vote down vote up
def __init__(self, outputDir=None, prefix="proc"):
        self.logs = []
        self.logs_cond = threading.Condition(threading.RLock())
        self.cmd_line = None
        self.running = False
        self.proc = None
        self.outputDir = outputDir
        self.logger = logging.getLogger(prefix) 
Example #27
Source File: util.py    From exposure with MIT License 5 votes vote down vote up
def __init__(self, target, args=(), kwargs={}):
    self.target = target
    self.args = args
    self.kwargs = kwargs
    self.condition = threading.Condition()
    self.result = None
    self.thread = threading.Thread(target=self.worker)
    self.stopped = False
    self.thread.daemon = True
    self.thread.start() 
Example #28
Source File: fig19_11.py    From PythonClassBook with GNU General Public License v3.0 5 votes vote down vote up
def __init__( self, threadName, semaphore ):
        "Initialize thread"

        threading.Thread.__init__( self, name = threadName )
        self.sleepTime = random.randrange( 1, 6 )

        # set the semaphore as a data attribute of the class
        self.threadSemaphore = semaphore

	# allow only one thread to access threadCount at a time
	self.threadCondition = threading.Condition() 
Example #29
Source File: CircularBuffer.py    From PythonClassBook with GNU General Public License v3.0 5 votes vote down vote up
def __init__( self ):
      """Set buffer, count, locations and condition variable"""

      # each element in list is a buffer      
      self.buffer = [ -1, -1, -1 ]
      
      self.occupiedBufferCount = 0   # count of occupied buffers
      self.readLocation = 0          # current reading index
      self.writeLocation = 0         # current writing index
      
      self.threadCondition = threading.Condition() 
Example #30
Source File: SynchronizedInteger.py    From PythonClassBook with GNU General Public License v3.0 5 votes vote down vote up
def __init__( self ):
      """Initialize integer, buffer count and condition variable"""
      
      self.buffer = -1  
      self.occupiedBufferCount = 0   # number of occupied buffers
      self.threadCondition = threading.Condition()