當前位置: 首頁>>代碼示例>>Python>>正文


Python threading.Condition方法代碼示例

本文整理匯總了Python中threading.Condition方法的典型用法代碼示例。如果您正苦於以下問題:Python threading.Condition方法的具體用法?Python threading.Condition怎麽用?Python threading.Condition使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在threading的用法示例。


在下文中一共展示了threading.Condition方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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() 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:20,代碼來源:pubSub.py

示例2: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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) 
開發者ID:sippy,項目名稱:rtp_cluster,代碼行數:23,代碼來源:Rtp_proxy_client_stream.py

示例3: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:20,代碼來源:queue.py

示例4: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:24,代碼來源:queue.py

示例5: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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..." ) 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:21,代碼來源:fig20_06.py

示例6: sync_fetch

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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'] 
開發者ID:binux,項目名稱:pyspider,代碼行數:24,代碼來源:tornado_fetcher.py

示例7: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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() 
開發者ID:Parrot-Developers,項目名稱:olympe,代碼行數:19,代碼來源:expectations.py

示例8: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:zhmcclient,項目名稱:python-zhmcclient,代碼行數:22,代碼來源:_notification.py

示例9: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:24,代碼來源:requeue.py

示例10: executeCommand

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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; 
開發者ID:rmawatson,項目名稱:PyEagle,代碼行數:19,代碼來源:Eaglepy.py

示例11: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:genialis,項目名稱:resolwe,代碼行數:21,代碼來源:circular_buffer.py

示例12: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 = [] 
開發者ID:westpa,項目名稱:westpa,代碼行數:18,代碼來源:core.py

示例13: synchronized

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:OpenMTC,項目名稱:OpenMTC,代碼行數:22,代碼來源:synchronized.py

示例14: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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 
開發者ID:NiklasRosenstein,項目名稱:myo-python,代碼行數:23,代碼來源:_device_listener.py

示例15: run

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import Condition [as 別名]
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) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:13,代碼來源:pubSub.py


注:本文中的threading.Condition方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。