Python threading.Condition() Examples

The following are 30 code examples for showing how to use threading.Condition(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: pubSub.py    License: MIT License 6 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 2
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 3
Project: jawfish   Author: war-and-code   File: queue.py    License: 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 4
Project: jawfish   Author: war-and-code   File: queue.py    License: 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 5
Project: PythonClassBook   Author: PythonClassRoom   File: fig20_06.py    License: GNU General Public License v3.0 6 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 6
Project: pyspider   Author: binux   File: tornado_fetcher.py    License: 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 7
Project: olympe   Author: Parrot-Developers   File: expectations.py    License: 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 8
Project: python-zhmcclient   Author: zhmcclient   File: _notification.py    License: Apache License 2.0 6 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 9
Project: browserscope   Author: elsigh   File: requeue.py    License: Apache License 2.0 6 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 10
Project: PyEagle   Author: rmawatson   File: Eaglepy.py    License: GNU Lesser General Public License v2.1 6 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 11
Project: resolwe   Author: genialis   File: circular_buffer.py    License: Apache License 2.0 6 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 12
Project: westpa   Author: westpa   File: core.py    License: 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 13
Project: meddle   Author: glmcdona   File: Queue.py    License: 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 14
Project: ironpython2   Author: IronLanguages   File: Queue.py    License: 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 15
Project: OpenMTC   Author: OpenMTC   File: synchronized.py    License: 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 16
Project: myo-python   Author: NiklasRosenstein   File: _device_listener.py    License: 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 17
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: pubSub.py    License: 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 18
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: pubSub.py    License: 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 19
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: producerConsumer.py    License: 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 20
Project: rtp_cluster   Author: sippy   File: DNRelay.py    License: 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 21
Project: rtp_cluster   Author: sippy   File: CLIManager.py    License: 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 22
Project: rtp_cluster   Author: sippy   File: Udp_server.py    License: 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 23
Project: rtp_cluster   Author: sippy   File: SipLogger.py    License: 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 24
Project: overhaul-distillation   Author: clovaai   File: comm.py    License: 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 25
Project: jawfish   Author: war-and-code   File: pool.py    License: 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
Project: lnd_grpc   Author: willcl-ark   File: utils.py    License: 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
Project: exposure   Author: yuanming-hu   File: util.py    License: 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
Project: PythonClassBook   Author: PythonClassRoom   File: fig19_11.py    License: 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
Project: PythonClassBook   Author: PythonClassRoom   File: CircularBuffer.py    License: 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
Project: PythonClassBook   Author: PythonClassRoom   File: SynchronizedInteger.py    License: 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()