我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用twisted.internet.defer.DeferredLock()。
def initServer(self): """Initialize the server after connecting to LabRAD.""" self.knownDevices = {} # maps (server, channel) to (name, idn) self.deviceServers = {} # maps device name to list of interested servers. # each interested server is {'target':<>,'context':<>,'messageID':<>} self.identFunctions = {} # maps server to (setting, ctx) for ident self.identLock = DeferredLock() # named messages are sent with source ID first, which we ignore connect_func = lambda c, (s, payload): self.gpib_device_connect(*payload) disconnect_func = lambda c, (s, payload): self.gpib_device_disconnect(*payload) mgr = self.client.manager self._cxn.addListener(connect_func, source=mgr.ID, ID=10) self._cxn.addListener(disconnect_func, source=mgr.ID, ID=11) yield mgr.subscribe_to_named_message('GPIB Device Connect', 10, True) yield mgr.subscribe_to_named_message('GPIB Device Disconnect', 11, True) # do an initial scan of the available GPIB devices yield self.refreshDeviceLists()
def __init__(self, *args, **kwargs): AMQClient.__init__(self, *args, **kwargs) if self.check_0_8(): self.replyToField = "reply to" else: self.replyToField = "reply-to" self.thriftBasicReturnQueueLock = defer.DeferredLock() self.thriftBasicReturnQueues = {}
def cleanup_deferred_locks(): """ Need to use this from within trial to cleanup the reactor before each run. """ SoledadDocumentWrapper._k_locks = defaultdict(defer.DeferredLock)
def _get_klass_lock(cls): """ Get a DeferredLock that is unique for this subclass name. Used to lock the access to indexes in the `get_or_create` call for a particular DocumentWrapper. """ return cls._k_locks[cls.__name__]
def __init__(self, doc_id=None, future_doc_id=None, **kwargs): self._doc_id = doc_id self._future_doc_id = future_doc_id self._lock = defer.DeferredLock() super(SoledadDocumentWrapper, self).__init__(**kwargs)
def __init__(self, maxPerSecond=0): self.maxPerSecond = maxPerSecond defer.DeferredLock.__init__(self)
def release(self): delay = self._nextDelay() self.reactor.callLater(delay, defer.DeferredLock.release, self)
def initServer(self): self.listeners = set() self.camera = AndorCamera() self.lock = DeferredLock() self.gui = AndorVideo(self)
def __init__(self, token, on_update, proxy=None, debug=False): self._lock = defer.DeferredLock() self._token = token self._proxy = proxy self._debug = debug assert callable(on_update) self._on_update = on_update
def test_cancelLockAfterAcquired(self): """ When canceling a L{Deferred} from a L{DeferredLock} that already has the lock, the cancel should have no effect. """ def _failOnErrback(_): self.fail("Unexpected errback call!") lock = defer.DeferredLock() d = lock.acquire() d.addErrback(_failOnErrback) d.cancel()
def test_cancelLockBeforeAcquired(self): """ When canceling a L{Deferred} from a L{DeferredLock} that does not yet have the lock (i.e., the L{Deferred} has not fired), the cancel should cause a L{defer.CancelledError} failure. """ lock = defer.DeferredLock() lock.acquire() d = lock.acquire() d.cancel() self.assertImmediateFailure(d, defer.CancelledError)
def __init__(self): self._tasks = iter(()) self._active_tasks = [] self.failures = 0 self.task_lock = defer.DeferredLock()
def __init__(self, timeout, _reactor=reactor): self.lock = defer.DeferredLock() self.deferred_subscribers = [] self._reactor = _reactor self._timeout = timeout self.timer = task.LoopingCall( self.notify, DirectorEvent("null", "No updates"), ) self.timer.clock = self._reactor
def __init__(self, file_path): """ Args: file_path: is the location of where the filesystem based lockfile should be written to. """ self._fs_lock = defer.DeferredFilesystemLock(file_path) self._mutex = defer.DeferredLock()
def testLock(self): lock = defer.DeferredLock() lock.acquire().addCallback(self._incr) self.failUnless(lock.locked) self.assertEquals(self.counter, 1) lock.acquire().addCallback(self._incr) self.failUnless(lock.locked) self.assertEquals(self.counter, 1) lock.release() self.failUnless(lock.locked) self.assertEquals(self.counter, 2) lock.release() self.failIf(lock.locked) self.assertEquals(self.counter, 2) self.assertRaises(TypeError, lock.run) firstUnique = object() secondUnique = object() controlDeferred = defer.Deferred() def helper(self, b): self.b = b return controlDeferred resultDeferred = lock.run(helper, self=self, b=firstUnique) self.failUnless(lock.locked) self.assertEquals(self.b, firstUnique) resultDeferred.addCallback(lambda x: setattr(self, 'result', x)) lock.acquire().addCallback(self._incr) self.failUnless(lock.locked) self.assertEquals(self.counter, 2) controlDeferred.callback(secondUnique) self.assertEquals(self.result, secondUnique) self.failUnless(lock.locked) self.assertEquals(self.counter, 3) lock.release() self.failIf(lock.locked)
def __init__(self, delegate, vhost, spec, heartbeat=0, clock=None, insist=False): FrameReceiver.__init__(self, spec) self.delegate = delegate # XXX Cyclic dependency self.delegate.client = self self.vhost = vhost self.channelFactory = type("Channel%s" % self.spec.klass.__name__, (self.channelClass, self.spec.klass), {}) self.channels = {} self.channelLock = defer.DeferredLock() self.outgoing = defer.DeferredQueue() self.work = defer.DeferredQueue() self.started = TwistedEvent() self.disconnected = TwistedEvent() # Fired upon connection shutdown self.closed = False self.queueLock = defer.DeferredLock() self.basic_return_queue = TimeoutDeferredQueue() self.queues = {} self.outgoing.get().addCallback(self.writer) self.work.get().addCallback(self.worker) self.heartbeatInterval = heartbeat self.insist = insist if clock is None: from twisted.internet import reactor clock = reactor self.clock = clock if self.heartbeatInterval > 0: self.checkHB = self.clock.callLater(self.heartbeatInterval * self.MAX_UNSEEN_HEARTBEAT, self.check_heartbeat) self.sendHB = LoopingCall(self.send_heartbeat) self.sendHB.clock = self.clock d = self.started.wait() d.addCallback(lambda _: self.reschedule_send_heartbeat()) d.addCallback(lambda _: self.reschedule_check_heartbeat()) # If self.started fails, don't start the heartbeat. d.addErrback(lambda _: None)
def __init__(self, list_path, state_space_parameters, hyper_parameters, epsilon=None, number_models=None): self.protocol = QConnection self.new_net_lock = DeferredLock() self.clients = {} # name of connection is key, each value is dict with {'connection', 'net', 'iters_sampled'} self.replay_columns = ['net', #Net String 'accuracy_best_val', 'iter_best_val', 'accuracy_last_val', 'iter_last_val', 'accuracy_best_test', 'accuracy_last_test', 'ix_q_value_update', #Iteration for q value update 'epsilon', # For epsilon greedy 'time_finished', # UNIX time 'machine_run_on'] self.list_path = list_path self.replay_dictionary_path = os.path.join(list_path, 'replay_database.csv') self.replay_dictionary, self.q_training_step = self.load_replay() self.schedule_or_single = False if epsilon else True if self.schedule_or_single: self.epsilon = state_space_parameters.epsilon_schedule[0][0] self.number_models = state_space_parameters.epsilon_schedule[0][1] else: self.epsilon = epsilon self.number_models = number_models if number_models else 10000000000 self.state_space_parameters = state_space_parameters self.hyper_parameters = hyper_parameters self.number_q_updates_per_train = 100 self.list_path = list_path self.qlearner = self.load_qlearner() self.check_reached_limit()
def testLock(self): lock = defer.DeferredLock() lock.acquire().addCallback(self._incr) self.assertTrue(lock.locked) self.assertEqual(self.counter, 1) lock.acquire().addCallback(self._incr) self.assertTrue(lock.locked) self.assertEqual(self.counter, 1) lock.release() self.assertTrue(lock.locked) self.assertEqual(self.counter, 2) lock.release() self.assertFalse(lock.locked) self.assertEqual(self.counter, 2) self.assertRaises(TypeError, lock.run) firstUnique = object() secondUnique = object() controlDeferred = defer.Deferred() def helper(self, b): self.b = b return controlDeferred resultDeferred = lock.run(helper, self=self, b=firstUnique) self.assertTrue(lock.locked) self.assertEqual(self.b, firstUnique) resultDeferred.addCallback(lambda x: setattr(self, 'result', x)) lock.acquire().addCallback(self._incr) self.assertTrue(lock.locked) self.assertEqual(self.counter, 2) controlDeferred.callback(secondUnique) self.assertEqual(self.result, secondUnique) self.assertTrue(lock.locked) self.assertEqual(self.counter, 3) d = lock.acquire().addBoth(lambda x: setattr(self, 'result', x)) d.cancel() self.assertEqual(self.result.type, defer.CancelledError) lock.release() self.assertFalse(lock.locked)