当前位置: 首页>>代码示例>>Python>>正文


Python Condition.acquire方法代码示例

本文整理汇总了Python中threading.Condition.acquire方法的典型用法代码示例。如果您正苦于以下问题:Python Condition.acquire方法的具体用法?Python Condition.acquire怎么用?Python Condition.acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Condition的用法示例。


在下文中一共展示了Condition.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SimpleRemoteCall

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class SimpleRemoteCall(object):
    returncode = None
    returned = False
    
    def signal(self):
        self.cond.acquire()
        self.returned = True
        self.cond.notify()
        self.cond.release()
        
    def errorHandler(self, error):
        self.returncode = error
        self.signal()
        
    def successHandler(self, object):
        self.returncode = object
        self.signal()
        
    def __call__(*arg, **kwargs):
        pass
        
    def __init__(self, remoteReference, *arg, **kwargs):
        self.cond = Condition()
        deref = remoteReference.callRemote(*arg, **kwargs)
        deref.addCallbacks(self.successHandler, self.errorHandler)
        
    def wait(self, timeout = None):
        self.cond.acquire()
        if not self.returned:
            self.cond.wait(timeout)
            
        self.cond.release()
        if not self.returned:
            raise TimeExpired('timeout')
开发者ID:snua12,项目名称:zlomekfs,代码行数:36,代码来源:remoteZfs.py

示例2: MessageQueue

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class MessageQueue(object):
    """The message queue used internally by Gossip."""

    def __init__(self):
        self._queue = deque()
        self._condition = Condition()

    def pop(self):
        self._condition.acquire()
        try:
            while len(self._queue) < 1:
                self._condition.wait()
            return self._queue.pop()
        finally:
            self._condition.release()

    def __len__(self):
        return len(self._queue)

    def __deepcopy__(self, memo):
        newmq = MessageQueue()
        newmq._queue = copy.deepcopy(self._queue, memo)
        return newmq

    def appendleft(self, msg):
        self._condition.acquire()
        try:
            self._queue.appendleft(msg)
            self._condition.notify()
        finally:
            self._condition.release()
开发者ID:yy860179277,项目名称:sawtooth-core,代码行数:33,代码来源:gossip_core.py

示例3: process_sequence

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
    def process_sequence(self, sequence):
        """
        @param sequence: the movement sequence to execute
        @return: dictionary of sensor readings
        """
        self.log.debug('process sequence')
        # parse the json message
        jseq = json.loads(sequence)
        moveseq = jseq['sequence']

        for moves in moveseq:
            self.log.debug('processing move %s' % moves)
            condition = Condition()
            thread_count = 0
            for move in moves:
                thread_count += 1
                servo_instruction = self.process_move(move)
                move_servo_thread = ServoThread(servo_instruction, self.pwm_queue, condition, thread_count, self.update_current_pulse)
                move_servo_thread.setDaemon(False)
                move_servo_thread.setName('Servo %d' % servo_instruction['channel'])
                move_servo_thread.start()
            condition.acquire()
            if thread_count > 0:
                condition.wait()
            # wait for all threads to finish before doing next loop
            condition.release()
开发者ID:margic,项目名称:pihex,代码行数:28,代码来源:controller.py

示例4: ZEventLoopThread

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class ZEventLoopThread(object):
    def __init__(self, cb=None):
        self._event_loop = None
        self._thr = Thread(target=self._thread_func)
        self._guard = Condition(Lock())
        self._thr_callback = cb

    def start_loop(self):
        self._thr.start()
        self._guard.acquire()
        while self._event_loop is None:
            self._guard.wait()

        return self._event_loop

    def _thread_func(self):
        # Note: create event loop in the new thread
        # instead in the constructor 
        event_loop = ZEventLoop()

        if self._thr_callback:
            self._thr_callback(event_loop)

        with self._guard:
            self._event_loop = event_loop
            self._guard.notify()

        event_loop.loop()
开发者ID:chenziliang,项目名称:src,代码行数:30,代码来源:z_event_loop_thread.py

示例5: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class ZumyROS:
    def __init__(self):
        self.zumy = Zumy()
        rospy.init_node("zumy_ros")
        self.cmd = (0, 0)
        rospy.Subscriber("cmd_vel", Twist, self.cmd_callback, queue_size=1)
        self.lock = Condition()
        self.rate = rospy.Rate(30.0)
        self.name = socket.gethostname()
        self.heartBeat = rospy.Publisher("/" + self.name + "/heartBeat", String, queue_size=5)
        self.imu_pub = rospy.Publisher("/" + self.name + "/imu", Imu, queue_size=1)
        self.imu_count = 0
        self.timestamp = time.time()
        self.publisher = rospy.Publisher("from_zumy", Float64, queue_size=1)
        self.msg = None

    def cmd_callback(self, msg):
        self.msg = msg
        self.timestamp = time.time()
        lv = 0.6
        la = 0.4
        v = msg.linear.x
        print v
        a = msg.angular.z
        print a
        r = lv * v + la * a
        l = lv * v - la * a
        self.lock.acquire()
        self.cmd = (l, r)
        self.lock.release()

    def run(self):
        while not rospy.is_shutdown():
            time_now = time.time()

            if time_now - self.timestamp > 0.5:
                self.cmd = (0, 0)

            self.lock.acquire()
            self.zumy.cmd(*self.cmd)
            imu_data = self.zumy.read_imu()
            self.lock.release()

            imu_msg = Imu()
            imu_msg.header = Header(self.imu_count, rospy.Time.now(), self.name)
            imu_msg.linear_acceleration.x = 9.81 * imu_data[0]
            imu_msg.linear_acceleration.y = 9.81 * imu_data[1]
            imu_msg.linear_acceleration.z = 9.81 * imu_data[2]
            imu_msg.angular_velocity.x = 3.14 / 180.0 * imu_data[3]
            imu_msg.angular_velocity.y = 3.14 / 180.0 * imu_data[4]
            imu_msg.angular_velocity.z = 3.14 / 180.0 * imu_data[5]
            self.imu_pub.publish(imu_msg)

            self.heartBeat.publish("I am alive from Glew")
            if self.msg != None:
                self.publisher.publish(self.msg.linear.y)
            self.rate.sleep()

        # If shutdown, turn off motors
        self.zumy.cmd(0, 0)
开发者ID:wuhy08,项目名称:GLEWproject_zumy,代码行数:62,代码来源:zumy_ros_bridge.py

示例6: Queue

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class Queue(object):
    def __init__(self):
        self.lock = Lock()
        self.cond = Condition(self.lock)
        self.data = []
        self.live = True

    def put(self, values):
        self.cond.acquire()
        self.data.extend(values)
        self.cond.notify()
        self.cond.release()

    def get(self):
        if not self.cond.acquire(False):
            return []
        self.cond.wait()
        result = self.data
        self.data = []
        self.cond.release()
        return result

    def close(self):
        self.cond.acquire()
        self.live = False
        self.cond.notify()
        self.cond.release()
开发者ID:Iffar,项目名称:makehuman_datagen,代码行数:29,代码来源:queue.py

示例7: SharedCell

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class SharedCell(object):
    """Shared data for the producer/consumer problem."""
    
    def __init__(self):
        self._data = -1
        self._writeable = True
        self._condition = Condition()

    def setData(self, data):
        """Producer's method to write to shared data."""
        self._condition.acquire()
        while not self._writeable:
            self._condition.wait()
        print "%s setting data to %d" % \
              (currentThread().getName(), data)
        self._data = data
        self._writeable = False
        self._condition.notify()
        self._condition.release()

    def getData(self):
        """Consumer's method to read from shared data."""
        self._condition.acquire()
        while self._writeable:
            self._condition.wait()
        print "%s accessing data %d" % \
              (currentThread().getName(), self._data)
        self._writeable = True
        self._condition.notify()
        self._condition.release()
        return self._data
开发者ID:gregpuzzles1,项目名称:Sandbox,代码行数:33,代码来源:pc2.py

示例8: Rtp_proxy_client_local

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class Rtp_proxy_client_local(object):
    is_local = True
    wi_available = None
    wi = None
    nworkers = None
    workers = None

    def __init__(self, global_config, address = '/var/run/rtpproxy.sock', \
      bind_address = None, nworkers = 1):
        self.address = address
        self.is_local = True
        self.wi_available = Condition()
        self.wi = []
        self.nworkers = nworkers
        self.workers = []
        for i in range(0, self.nworkers):
            self.workers.append(_RTPPLWorker(self))

    def send_command(self, command, result_callback = None, *callback_parameters):
        self.wi_available.acquire()
        self.wi.append((command, result_callback, callback_parameters))
        self.wi_available.notify()
        self.wi_available.release()

    def reconnect(self, address, bind_address = None):
        self.shutdown()
        self.address = address
        self.workers = []
        for i in range(0, self.nworkers):
            self.workers.append(_RTPPLWorker(self))

    def shutdown(self):
        for rworker in self.workers:
            rworker.shutdown()
        self.workers = None
开发者ID:zfjia,项目名称:b2bua,代码行数:37,代码来源:Rtp_proxy_client_local.py

示例9: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class MultiProcBuilder:

    def __init__(self, makeFile, param):

        makeFileList = []
        index = 1
        while os.path.isfile(os.getcwd() + '\\' + makeFile.replace('.mak', 'C' + str(index) + '.mak')):        
            makeFileList.append(makeFile.replace('.mak', 'C' + str(index) + '.mak'))
            index = index + 1
            #TODO externalizar a extensoes para parametros configuraveis
        makeFileLinker = makeFile.replace('.mak', 'L.mak')

        self.condition = Condition()
        self.output = []
        self.group = MakeGroup(makeFileList, makeFileLinker, self.output, self.condition, param)

    def start(self):
        """Dispara compilacao multiprocessada"""

        self.group.start()

    def readMsg(self):

        self.condition.acquire()
        out = ""
        if len(self.output) == 0 and self.group.isAlive():
            self.condition.wait()
        while len(self.output) > 0:
            out += self.output.pop(0)
        self.condition.release()

        return out

    def getResult(self):
        return self.group.status    
开发者ID:rafaelxy,项目名称:python,代码行数:37,代码来源:mpbuild.py

示例10: test_call_self

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
    def test_call_self(self):
        m = Mock()
        cond = Condition()
        self._recv_call_id = None

        def event_cb(_, evt):
            if evt.type == EventType.call_invite:
                m()
                self._recv_call_id = evt.request.call_id
            # condition of event callback returning
            cond.acquire()
            cond.notify()
            cond.release()

        self.ctx.event_callback = event_cb
        # start call:
        # build and send invitation message
        cond.acquire()
        with self.ctx.lock:
            msg = call.InitInvite(
                self.ctx,
                to_url='sip:{0[0]}:{0[1]}'.format(self.listen_address),
                from_url='sip:{0[0]}:{0[1]}'.format(self.listen_address),
            )
            send_call_id = msg.call_id
            self.ctx.call_send_init_invite(msg)
        # wait event result!
        cond.wait(1)
        cond.release()
        # assertion
        self.assertEqual(m.call_count, 1)
        self.assertEqual(self._recv_call_id, send_call_id)
开发者ID:tanbro,项目名称:exosip2ctypes,代码行数:34,代码来源:test_call.py

示例11: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class ServerLock:
    """
    Class to be used for locking entry and exit to the venue server.
    Mostly just a wrapper around a normal lock, but adds logging support.
    """

    verbose = 0

    def __init__(self, name = ""):
        if self.verbose:
            log.debug("Create server lock %s", name)
        self.lock = Condition(Lock())
        self.name = name

    def acquire(self):
        if self.verbose:
            c = (traceback.extract_stack())[-2]
            fileName = c[0]
            line = c[1]
            log.debug("Try to acquire server lock %s...      %s:%s", self.name, fileName, line)

        self.lock.acquire()

        if self.verbose:
            log.debug("Try to acquire server lock %s...done  %s:%s", self.name, fileName, line)

    def release(self):
        if self.verbose:
            c = (traceback.extract_stack())[-2]
            fileName = c[0]
            line = c[1]
            log.debug("Releasing server lock %s  %s:%s", self.name, fileName, line)
        self.lock.release()
开发者ID:aabhasgarg,项目名称:accessgrid,代码行数:35,代码来源:Utilities.py

示例12: GridGenerationUpdateThread

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class GridGenerationUpdateThread(Thread):
    disconnect = False
    elecgen    = None
    sleeper    = None
    def __init__(self, parent):
        Thread.__init__(self)
        self.disconnect = False
        self.elecgen = parent
        self.ngdata  = ElectricityGenerationDataSource()
        self.sleeper = Condition()
    def stopUpdates(self):
        self.disconnect = True
        self.sleeper.acquire()
        self.sleeper.notify()
        self.sleeper.release()
    def run(self):
        while self.disconnect == False:
            emxml = self.ngdata.DownloadRealtimeXML()
            try: 
                self.elecgen.energyMix = self.ngdata.ParseRealtimeXML(emxml)
            except Exception, exc:
                trc.Error("failed to parse realtime xml")
                trc.Error(str(emxml))
                trc.Error(repr(exc))
                trc.Error(repr(exc.message))
            # go to sleep for a while - the realtime data doesn't update very
            #  often, so no need to download it constantly!
            self.sleeper.acquire()
            self.sleeper.wait(180)
            self.sleeper.release()
开发者ID:jmhdz,项目名称:currentcostgui,代码行数:32,代码来源:electricitygeneration.py

示例13: SafeLoopArray

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class SafeLoopArray(object):
	def __init__(self , data, lengh = 10):
		self._lengh = lengh
		self._data	= []
		self._index = 0;
		self._lock  = Condition(Lock())

		for i in range(lengh):
			self._data.append(data)
			

	def add(self , data):
		self._lock.acquire()
		try:
			i = self._index%self._lengh
			#print "self._lengh = {0},self._index={1},i={2}".format(self._lengh,self._index, i)
			self._data[i] = data
			self._index = self._index+1
		finally:
			self._lock.release()

	def get(self , pos):
		if (pos >= self._lengh):
			print("out of range")
			return None
		self._lock.acquire()
		try:
			return self._data[pos]
		finally:
			self._lock.release()
开发者ID:Adam57,项目名称:Crawler,代码行数:32,代码来源:safe_loop_array.py

示例14: __init__

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
class Barrier:
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.count = num_threads
        self.iter = 0
        self.cond = Condition()

    def wait(self):
        self.cond.acquire()
        i = self.iter
        self.count -= 1
        if self.count == 0:
            self.iter += 1
            self.count = self.num_threads
            self.cond.notify_all()
            self.cond.release()
            return True
        # Release lock and block this thread until notified/woken.
        # Allow for spurious wake-ups.
        while 1:
            self.cond.wait(None)
            if i != self.iter:
                break
        self.cond.release()
        return False
开发者ID:OxfordSKA,项目名称:OSKAR,代码行数:27,代码来源:barrier.py

示例15: wait_statement

# 需要导入模块: from threading import Condition [as 别名]
# 或者: from threading.Condition import acquire [as 别名]
    def wait_statement(self, wtime, N=5):
        '''

        '''

        start_time = time.time()
        if self.debug:
            time.sleep(1)

        else:
            if isinstance(wtime, str):
                wtime = float(self._get_interpolation_value(wtime))

            if wtime > N:
                c = Condition()
                c.acquire()
                wd = WaitDialog(wtime=wtime,
                                    condition=c,
                                    parent=self)
                do_later(wd.edit_traits, kind='livemodal')
                c.wait()
                c.release()
                do_later(wd.close)
            else:
                time.sleep(wtime)

        msg = 'actual wait time %0.3f s' % (time.time() - start_time)
        self.log_statement(msg)
开发者ID:softtrainee,项目名称:arlab,代码行数:30,代码来源:extraction_line_script.py


注:本文中的threading.Condition.acquire方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。