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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #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: _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 #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: 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 #11
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 #12
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 #13
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 #14
Source File: mapping.py    From rgbd_ptam with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, graph, params):
        super().__init__(graph, params)

        self._requests_cv = Condition()
        self._requests = [False, False]   # requests: [LOCKWINDOW_REQUEST, PROCESS_REQUEST]

        self._lock = Lock()
        self.locked_window = set()
        self.status = defaultdict(bool)
        
        self._queue = Queue()
        self.maintenance_thread = Thread(target=self.maintenance)
        self.maintenance_thread.start() 
Example #15
Source File: dispatch.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def __init__(self, timeout=10):
        super().__init__(name='Dispatcher')
        self._timeout = timeout
        self._msg_type_handlers = {}
        self._in_queue = queue.PriorityQueue()
        self._send_message = {}
        self._send_last_message = {}
        self._message_information = {}
        self._condition = Condition()
        self._dispatch_timers = {}
        self._priority = {}
        self._preprocessors = {} 
Example #16
Source File: client_handlers.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def __init__(self, batch_tracker):
        self._batch_tracker = batch_tracker
        self._wait_condition = Condition()
        self._statuses = None 
Example #17
Source File: utils.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, count):
        self._count = count
        # Dict[tag, next_sequence_number].
        self._tag_sequences = defaultdict(int)
        self._lowest_sequence = {}
        self._lock = threading.Lock()
        self._condition = threading.Condition(self._lock)
        # Dict[tag, List[sequence_number]]
        self._pending_release = {} 
Example #18
Source File: pool.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __init__(self, cache, callback):
        self._cond = threading.Condition(threading.Lock())
        self._job = job_counter.next()
        self._cache = cache
        self._ready = False
        self._callback = callback
        cache[self._job] = self 
Example #19
Source File: run_streaming.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition() 
Example #20
Source File: run_capture_image.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition() 
Example #21
Source File: updater.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        threading.Thread.__init__(self)
        self.paused = False
        # self.pause_cond = threading.Condition(threading.Lock())
        self.can_run = threading.Event()
        self.pause()
        self.status = -1
        self.updateIndex = None
        # self.run() 
Example #22
Source File: future.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def __init__(self, correlation_id, request=None, callback=None,
                 timeout=None, timer_ctx=None):
        self.correlation_id = correlation_id
        self._request = request
        self._result = None
        self._condition = Condition()
        self._create_time = time.time()
        self._callback_func = callback
        self._reconcile_time = None
        self._timeout = timeout
        self._timer_ctx = timer_ctx 
Example #23
Source File: scheduler.py    From classification-of-encrypted-traffic with MIT License 5 votes vote down vote up
def __init__(self, jobs, runner):
        threading.Thread.__init__(self)
        self.setName('scheduler')

        self.__runner = runner
        self.__jobs = jobs
        heapq.heapify(self.__jobs)

        self.__running = False
        self.__signal = threading.Condition() 
Example #24
Source File: test_config.py    From mars with Apache License 2.0 5 votes vote down vote up
def testMultiThreadConfig(self):
        options.register_option('a.b.c', 1)
        assert_equal = self.assertEqual

        class T(threading.Thread):
            def __init__(self, is_first, condition):
                super().__init__()
                self.is_first = is_first
                self.condition = condition

            def run(self):
                self.condition.acquire()
                if self.is_first:
                    options.a.b.c = 2
                    self.condition.notify()
                else:
                    self.condition.wait()
                    assert_equal(options.a.b.c, 1)
                self.condition.release()

        try:
            cond = threading.Condition()
            a = T(True, cond)
            b = T(False, cond)
            b.start()
            a.start()
            a.join()
            b.join()
        finally:
            options.unregister_option('a.b.c') 
Example #25
Source File: timer.py    From makerspace-auth with Apache License 2.0 5 votes vote down vote up
def __init__(self, event_queue, config_name, callback):
        super(Timer, self).__init__(event_queue, config_name)
        self.set_queue = queue.Queue(1)
        self.cancel_condition = threading.Condition()
        self.callback = callback 
Example #26
Source File: MultiBot.py    From PokemonGo-Bot with MIT License 5 votes vote down vote up
def __init__(self):
        threading.Thread.__init__(self)
        self.paused = True  # start out paused
        self.state = threading.Condition()
        self.Manager = Manager 
Example #27
Source File: cnn_util.py    From benchmarks with Apache License 2.0 5 votes vote down vote up
def __init__(self, parties):
    """Create a barrier, initialised to 'parties' threads."""
    self.cond = threading.Condition(threading.Lock())
    self.parties = parties
    # Indicates the number of waiting parties.
    self.waiting = 0
    # generation is needed to deal with spurious wakeups. If self.cond.wait()
    # wakes up for other reasons, generation will force it go back to wait().
    self.generation = 0
    self.broken = False 
Example #28
Source File: Eaglepy.py    From PyEagle with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        
        self.connectData = None
        self.queuedRequests       = []
        self.sessionID            = None
        self.serverThread         = None
    
        self.commandQueueLock = Lock() 
        self.commandQueue = []
        
        self.shuttingDown = False 
        self.shutdownCondition = Condition()
        self.commandCondition = {}
        
        HTTPServer.__init__(self,("127.0.0.1",7697),EagleRemoteHandler ) 
Example #29
Source File: analyzer.py    From malss with MIT License 5 votes vote down vote up
def __init__(self, mdl, X, y):
        super().__init__()
        self.mdl = mdl
        self.X = X
        self.y = y
        self.con = Condition() 
Example #30
Source File: comm.py    From EMANet with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self._result = None
        self._lock = threading.Lock()
        self._cond = threading.Condition(self._lock)