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


Python Lock.acquire方法代码示例

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


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

示例1: BatchInsertCollector

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class BatchInsertCollector():
    def __init__(self, cur, table_name, header=None, threshold=1000000):
        if not isinstance(cur, MyCursor):
            raise TypeError
        self.cur = cur
        self.table_name = table_name
        print 'lyc here'
        print table_name
        if header is None:
            print 'this way'
            self.header = cur.get_header(table_name)
        else:
            print 'that way'
            self.header = header
        print 'I have a header'
        self.sql_header = ''
        self.cur_len = 0
        self.reset_header()
        self.threshold = threshold
        self.values = []
        self.stat_total = 0
        self.mutex = Lock()
        print 'initial finish'

    def __del__(self):
        self.flush()
        self.cur.con.commit()

    def reset_header(self):
        self.sql_header = 'insert into %s (%s) values ' % (self.table_name, ','.join(self.header))
        self.cur_len = len(self.sql_header)

    def flush(self):
        if len(self.values) == 0:
            return
        self.cur.cur.execute(self.sql_header + ','.join(self.values))
        self.cur_len = len(self.sql_header)
        self.cur.con.commit()
        print 'flush called: %d records, total %d records' % (len(self.values), self.stat_total)
        self.values = []

    def append(self, data):
        assert isinstance(data, DictItem)
        self.mutex.acquire()

        def find(val):
            if val not in data.fields:
                return u"''"
            else:
                return u"'%s'" % unicode(data[val])

        cvalues = u','.join(map(find, self.header))
        val1 = u"(%s)" % cvalues
        # print self.cur_len
        if self.cur_len + len(val1) > self.threshold:
            self.flush()
        self.values.append(val1)
        self.cur_len += len(val1) + 1
        self.stat_total += 1
        self.mutex.release()
开发者ID:hdl730,项目名称:WeiboSpider,代码行数:62,代码来源:mycursor.py

示例2: _CoreScheduleThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class _CoreScheduleThread(Thread):
    def __init__(self,threadpool):
        self.scheduletasks = [];
        self.tasklock = Lock();
        self.condition = Condition(Lock())
        self.threadpool = threadpool
        Thread.__init__(self)

    def run(self):
        while True:
            self.condition.acquire()
            if len(self.scheduletasks) == 0:
                self.condition.wait();
            else:
                task = self.scheduletasks.pop(0)
                if dates.current_timestamps()>=task.nexttime: 
                    self.threadpool.execute(task.function,*task.args,**task.kwargs)
                    task.nexttime = dates.current_timestamps()+task.period;
                else:
                    self.condition.wait(task.nexttime-dates.current_timestamps())
                self.addtask(task)
            self.condition.release()

    
    def addtask(self,task): # copy on write
        self.tasklock.acquire()
        tasks = [ t for t in self.scheduletasks ]
        tasks.append(task)
        tasks.sort(key=lambda task:task.nexttime)
        self.scheduletasks = tasks
        self.tasklock.release()
开发者ID:IMISME,项目名称:yuntao.py,代码行数:33,代码来源:executors.py

示例3: WorkerTask

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class WorkerTask(object):
    """
    This class used to represent page loading task
    """
    def __init__(self, args, routine, user_data = None):
        self._lock_complete = Lock()
        self.__complete = False
        self.gathered = False
        self.args = args
        if callable(routine):
            self.routine = routine
        else:
            raise AttributeError('<routine> argument should be callable function')
        self.user_data = user_data
        self.result = []
        self.thread = None

    def _get_complete(self):
        """complete property getter"""
        self._lock_complete.acquire()
        complete = self.__complete
        self._lock_complete.release()
        return complete

    def _set_complete(self, state):
        """complete property setter"""
        if type(state) != types.BooleanType:
            raise TypeError('state should be boolean')
        self._lock_complete.acquire()
        self.__complete = state
        self._lock_complete.release()

    complete = property(_get_complete, _set_complete)
开发者ID:ktisha,项目名称:ebook-service,代码行数:35,代码来源:WorkerTask.py

示例4: WaitCursor

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class WaitCursor(Thread):
    """A waiting cursor for long operation that
    catch output and flush it after waiting"""
    def __init__(self):
        self.state = "WAIT"
        self.lock = Lock()           # Lock used to synchronise IO and cursor stop
        Thread.__init__(self)

    def run(self):
        """Method executed when the thread object start() method is called"""

        realStdout = sys.stdout # Backup stdout
        tmpStdout = StringIO()  # Store here all data output during waiting state
        sys.stdout = tmpStdout  # Capture stdout
        cursorState = ("-", "\\", "|", "/")
        i = 0
        self.lock.acquire()
        while self.state == "WAIT":
            realStdout.write(cursorState[i % 4])
            realStdout.flush()
            sleep(0.1)
            realStdout.write("\b")
            i += 1

        # Restore standard output and print temp data
        sys.stdout = realStdout
        sys.stdout.write(tmpStdout.getvalue())
        sys.stdout.flush()
        self.lock.release()

    def stop(self):
        self.state = "STOP"
        self.lock.acquire() # Wait end of IO flush before returning
开发者ID:sdelcros,项目名称:pysql,代码行数:35,代码来源:pysqlhelpers.py

示例5: handle

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
	def handle(self):
		#try:
			data, socket = self.request

			lock = Lock()
			lock.acquire()

			DataOffset    = struct.unpack('<H',data[139:141])[0]
			BrowserPacket = data[82+DataOffset:]
			ReqType       = RequestType(BrowserPacket[0])

			Domain = Decode_Name(data[49:81])
			Name   = Decode_Name(data[15:47])
			Role1  = NBT_NS_Role(data[45:48])
			Role2  = NBT_NS_Role(data[79:82])
			Fprint = WorkstationFingerPrint(data[190:192])
			Roles  = ParseRoles(data[192:196])

			print text("[BROWSER] Request Type : %s" % ReqType)
			print text("[BROWSER] Address      : %s" % self.client_address[0])
			print text("[BROWSER] Domain       : %s" % Domain)
			print text("[BROWSER] Name         : %s" % Name)
			print text("[BROWSER] Main Role    : %s" % Role1)
			print text("[BROWSER] 2nd Role     : %s" % Role2)
			print text("[BROWSER] Fingerprint  : %s" % Fprint)
			print text("[BROWSER] Role List    : %s" % Roles)

			RAPThisDomain(self.client_address[0], Domain)

			lock.release()
开发者ID:0xicl33n,项目名称:Potato,代码行数:32,代码来源:BrowserListener.py

示例6: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class Queue:
	"""Command queue class
	"""
	def __init__(self):
		self.lock = Lock()
		self.locks = {}
	
	def queue(self, command, *args):
		check = inspect.getargspec(command)
		cmdname = command.__name__ if command.__name__ else "uknown_cmd"
		if len(check[0]) != len(args):
			logging.warn("Queue command '%s' expected %u args, got %u!" % (cmdname, len(check[0]), len(args)))
			
		# If we have enough args, try running the command
		if len(args) >= len(check[0]):
			args = args[:len(check[0])] # Resize arg list if needed
			ret = None
			server = args[0]
			self.lock.acquire()
			if not server in self.locks:
				self.locks[server] = Lock()
			self.lock.release()
			
			self.locks[server].acquire()
			# Run in an enclosure, so as to be able to release lock if it fails
			try:
				ret = command(*args)
			except Exception as err:
				logging.warn("Queue command returned error: %s" % err)
			self.locks[server].release()
			
			if ret:
				return ret
		return None
开发者ID:Humbedooh,项目名称:dsnmp,代码行数:36,代码来源:daemon.py

示例7: InMemoryItemValue

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class InMemoryItemValue(object):
  _lock = None
  """:type _lock Lock"""

  def __init__(self, value=None, expire_in=None):
    self._lock = Lock()
    self._value = value
    self._expire_in = None
    self._expire_in_time = None

    self.update_expire_time(expire_in)

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, val):
    self._lock.acquire()
    self._value = val
    self._expire_in = datetime.now() + timedelta(seconds=float(self._expire_in_time)) if self._expire_in_time else None
    self._lock.release()

  def update_expire_time(self, t):
    self._expire_in_time = t

  @property
  def is_expired(self):
    return (self._expire_in - datetime.now()).days < 0 if self._expire_in else False
开发者ID:hapylestat,项目名称:appcore,代码行数:31,代码来源:in_memory.py

示例8: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class Promise:
  def __init__(self):
    self.value = None
    self.mutex = Lock()
    self.callbacks = []

  def updateValue(self, new_value):
    if (self.mutex.acquire(blocking = False) and self.value is None):
      self.value = new_value
      for cb in self.callbacks:
        cb(new_value)
      self.mutex.release()
    else:
      raise RuntimeError("cannot set the value of an already resolved promise")

  def addCallback(self, cb):
    self.mutex.acquire(blocking = True)
    self.callbacks.append(cb)
    self.mutex.release()
    return self

  def map(self, f):
    fp = Promise()
    def chain(v):
      fp.updateValue(f(v))
    self.addCallback(chain)
    return fp

  def flatMap(self, f):
    fp = Promise()
    def chain(v):
      f(v).addCallback(fp.updateValue)
    self.addCallback(chain)
    return fp
开发者ID:entombedvirus,项目名称:GitGutter,代码行数:36,代码来源:promise.py

示例9: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class TUNERS:
    def __init__(self, str):
        from threading import Lock

        tuners = "".join(str.split()) # remove white space
        tuners = tuners.split(',')
        tuners = [tuple(x.split(':')[0:2]) for x in tuners]
        # Add priority
        self.tuner_list = [(i, v[0], v[1]) for i,v in enumerate(tuners)]
        heapq.heapify(self.tuner_list)
        self.lock = Lock()

    def get_tuner(self):
        self.lock.acquire()
        try:
            tuner = heapq.heappop(self.tuner_list)
        except IndexError:
            tuner = None
        finally:
            self.lock.release()
        return tuner

    def put_tuner(self, tuner):
        self.lock.acquire()
        heapq.heappush(self.tuner_list, tuner)
        self.lock.release()
开发者ID:astondg,项目名称:hdhomerun_recorder,代码行数:28,代码来源:recorder.py

示例10: TfBroadcasterThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class TfBroadcasterThread(Thread):
    def __init__(self,child_frame,parent_frame,tf_br=None):
        Thread.__init__(self)
        rospy.loginfo("Initializing tf broadcaster with child frame "+child_frame+" and parent frame "+parent_frame)
        if tf_br is None:
            self.tf_br = tf.TransformBroadcaster()
        else:
            self.tf_br = tf_br
        self.translation = None
        self.quaternion = None
        self.child_frame = child_frame
        self.parent_frame = parent_frame
        self.has_transformation=False
        self.lock=Lock()
            
    def set_transformation(self,translation,quaternion):
        self.lock.acquire()
        self.translation = translation
        self.quaternion = quaternion
        self.lock.release()
        self.has_transformation =True

    def run(self):
        while not rospy.is_shutdown():
            try:
                if self.has_transformation:
                    self.lock.acquire()
                    self.tf_br.sendTransform(self.translation ,self.quaternion , rospy.Time.now(), self.child_frame,self.parent_frame)
                    self.lock.release()
            except Exception,e:
                print 'TfBroadcasterThread:',e
开发者ID:kuka-isir,项目名称:depth_cam_extrinsics_calib,代码行数:33,代码来源:compute_transform_6d.py

示例11: PandoraPool

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class PandoraPool(object):
	def __init__(self, poolSize, proxy=None, expireTime=3600):
		self.size = poolSize
		self.proxy = proxy
		self.expire = expireTime
		self.pool = [self.createPandoraAgent() for i in xrange(self.size)]
		self.mutex = Lock()

	def createPandoraAgent(self):
		return PandoraAgent(datetime.now() + timedelta(0, self.expire), self.proxy)

	def refreshPandoraAgent(self, agent):
		if agent.isExpired():
			agent.authenticate_connection()
			agent.setExpireDate(datetime.now() + timedelta(0, self.expire))
		return agent

	def getAgent(self):
		try:
			return self.refreshPandoraAgent(self.pool.pop())
		except IndexError:
			return self.createPandoraAgent()

	def hasAvailableConnections(self):
		return len(self.pool) > 0

	def releaseAgent(self, agent):
		self.mutex.acquire()
		if len(self.pool) < self.size:
			self.pool.append(agent)
		self.mutex.release()
开发者ID:elElmo,项目名称:walkman,代码行数:33,代码来源:pandora_pool.py

示例12: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class DebuggingLock:
    def __init__(self, name):
        self.lock = Lock()
        self.name = name

    def acquire(self, blocking = 1):
        self.print_tb("Acquire lock")
        self.lock.acquire(blocking)
        self.logmsg("===== %s: Thread %s acquired lock\n"%
            (self.name, currentThread().getName()))

    def release(self):
        self.print_tb("Release lock")
        self.lock.release()

    def logmsg(self, msg):
        loglock.acquire()
        logfile.write(msg + "\n")
        logfile.flush()
        loglock.release()

    def print_tb(self, msg):
        self.logmsg(".... %s: Thread %s attempting to %s\n"% \
                    (self.name, currentThread().getName(), msg) + \
                    "\n".join(traceback.format_list(traceback.extract_stack())))
开发者ID:Deepanshu2017,项目名称:offlineimap,代码行数:27,代码来源:debuglock.py

示例13: DataWindow

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class DataWindow(Thread):
    def __init__(self,data_adapter):
        Thread.__init__(self)
        self.win = N.zeros((100,3))
        self.winlock = Lock()
        self.data_adapter = data_adapter
    
    def run(self):
        self.data_adapter.start()
        self.running = True
        while self.running:
            self.winlock.acquire()
            try:
                while 1:
                    newdata = self.data_adapter.q.get(block=False)
                    self.win[:-1,:] = self.win[1:,:]
                    self.win[-1,:] = newdata[1:]
            except Queue.Empty:
                pass
            finally:
                self.winlock.release()
        self.data_adapter.stop()
    
    def stop(self):
        self.running = False
开发者ID:NickFoubert,项目名称:adxl-visualize,代码行数:27,代码来源:viz.py

示例14: run

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
def run(conn):
    """Function to handle running implosion generation in separate :py:class:`multithreading.Process`

    :param conn: A connection, i.e. one end of a `Pipe()`
    """
    # Need duck-checking instead of real type-checking...
    assert hasattr(conn, 'send') and hasattr(conn, 'recv')

    # Get the implosion object from the pipe:
    imp = conn.recv()
    assert isinstance(imp, Implosion)

    connLock = Lock()

    # Run in a separate thread in this process:
    def impRun():
        nonlocal imp, conn
        try:
            imp.generate()
        except Exception as e:
            connLock.acquire()
            conn.send(e)
            connLock.release()

    t = Thread(target=impRun)
    t.start()

    while t.is_alive():
        connLock.acquire()
        conn.send(imp.progress())
        connLock.release()
        time.sleep(0.01)

    # When the thread is done, send the Implosion object back:
    conn.send(imp)
开发者ID:azylstra,项目名称:impy,代码行数:37,代码来源:ImplosionRunner.py

示例15: DPMClient

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import acquire [as 别名]
class DPMClient():   
    def __init__(self, uid=None, key=None):
        self._lock = Lock()
        self._uid = uid
        self._key = None
        if key:
            self._key = rsa.PublicKey.load_pkcs1(key)
      
    def request(self, addr, port, buf):
        self._lock.acquire()
        try:
            return self._request(addr, port, buf)
        finally:
            self._lock.release()
    
    def _request(self, addr, port, buf):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((addr, port))
        try:
            if self._key:
                stream = Stream(sock, uid=self._uid, key=self._key)
            else:
                stream = Stream(sock)
            stream.write( buf)
            if self._key:
                stream = Stream(sock)
            _, _, res = stream.readall()
            return res
        finally:
            sock.close()
开发者ID:tx626,项目名称:dpm,代码行数:32,代码来源:dpmclient.py


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