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


Python Lock.locked方法代码示例

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


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

示例1: Condition

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Condition(object):
    "Pipe-based condition uses poll to mimic build-in Condition"
    MSECSMAX = 0x7FFFFFFF
    def __init__ (self):
        self._lock = Lock()
        self._lockset = set()
        self._poll = select.poll()
        self._readfd, self._writefd = os.pipe()
        self._poll.register(self._readfd, select.POLLIN)
        super(Condition, self).__init__()
    def acquire(self):
        return self._lock.acquire()
    def release(self):
        return self._lock.release()
    def locked(self):
        return self._lock.locked()
    def wait(self, timeout=None):
        assert self._lock.locked(), 'wait called on un-acquire()d lock'
        waitlock = allocate_lock()
        waitlock.acquire()
        self._lockset.add(waitlock)
        self._lock.release()
        try:
            if timeout is None:
                self._waituntil(waitlock)
            else:
                self._waitupto(timeout, waitlock)
        finally:
            self._lock.acquire()
            if waitlock.acquire(0):
                os.read(self._readfd, 1)
            self._lockset.remove(waitlock)
    def _waitupto(self, timeout, waitlock):
        startuptime = uptime.secs()
        while not timeout < 0:
            msecs = min(timeout * 1000, self.MSECSMAX)
            readable = self._pollreadable(msecs)
            if waitlock.locked():
                curuptime = uptime.secs()
                lapsetime = curuptime - startuptime
                timeout = timeout - lapsetime
            else:
                break
        else:
            return False
        return True
    def _waituntil(self, waitlock):
        while waitlock.locked():
            self._pollreadable()
    def _pollreadable(self, timeout = None):
        try:
            return self._poll.poll(timeout)
        except select.error, error:
            msglog.log('broadway', msglog.types.WARN, 
                       'Notifier ignoring %s' % (error,))
        return False
开发者ID:mcruse,项目名称:monotone,代码行数:58,代码来源:pipebased.py

示例2: LockableClass

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
        class LockableClass(object):
            def __init__(self):
                self._lock = Lock()

            def test_method(self):
                lock_state = self._lock.locked()  # pylint: disable=no-member
                return lock_state

            @synchronized
            def sync_test_method(self):
                lock_state = self._lock.locked()  # pylint: disable=no-member
                return lock_state
开发者ID:jaymzh,项目名称:anaconda,代码行数:14,代码来源:iutil_test.py

示例3: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class SuccessLock:
    def __init__(self):
        self.lock = Lock()
        self.pause = Lock()
        self.code = 0L
        self.success = False
        self.finished = True

    def reset(self):
        self.success = False
        self.finished = False

    def set(self):
        self.lock.acquire()
        if not self.pause.locked():
            self.pause.acquire()
        self.first = True
        self.code += 1L
        self.lock.release()
        return self.code

    def trip(self, code, s = False):
        self.lock.acquire()
        try:
            if code == self.code and not self.finished:
                r = self.first
                self.first = False
                if s:
                    self.finished = True
                    self.success = True
                return r
        finally:
            self.lock.release()

    def give_up(self):
        self.lock.acquire()
        self.success = False
        self.finished = True
        self.lock.release()

    def wait(self):
        self.pause.acquire()

    def unwait(self, code):
        if code == self.code and self.pause.locked():
            self.pause.release()

    def isfinished(self):
        self.lock.acquire()
        x = self.finished
        self.lock.release()
        return x    
开发者ID:gitrab,项目名称:tau-p2pvod-2014a,代码行数:54,代码来源:Rerequester.py

示例4: Fork

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Fork():
	"""
	Fork is a shared resource among Philosophers. A Fork
	can only be held by one Philosopher at a time
	"""
	counter = 0
	timeout = 2 # in seconda

	def __init__(self):
		self.lock = Lock()
		self.id = Fork.counter 
		Fork.counter += 1

	def is_used(self):
		return self.lock.locked()

	def pickup(self):
		start = time.time()
		got_lock = False
		while time.time() - start < self.timeout and not got_lock:
			got_lock = self.lock.acquire(0)
		if not got_lock:
			logging.error('Deadlock')
			exit()

	def putdown(self):
		self.lock.release()
开发者ID:piratefsh,项目名称:dailyprogrammer,代码行数:29,代码来源:dining_philosophers.py

示例5: SingleThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class SingleThread():
    def __init__(self, progressbar):
        self.lock = Lock()
        self.progressbar = progressbar
    
    def run_with_progressbar(self, method, args=None, text=None, no_thread=False):
        if no_thread:
            if method and args:
                method(args)
            if method:
                method()
        else:
            self.progressbar.start(text)
            self._run(method, args)
                
    def _run(self, method, args=None):
        if not self.lock.locked():            
            self.lock.acquire()            
            thread.start_new_thread(self._thread_task, (method, args,))
        else:
            logging.warning("Thread not finished" + str(method) + str(args))    
    
    def _thread_task(self, method, args):
        try:
            if method and args:
                method(args)
            elif method:
                method()
            time.sleep(0.1)
        except Exception, e:
            logging.error(method.__name__ + "(" + str(args) + "):" + str(e))
        finally:
开发者ID:matttbe,项目名称:foobnix,代码行数:34,代码来源:single_thread.py

示例6: BlaLock

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class BlaLock(object):
    """
    Simple wrapper class for the thread.lock class which only raises an
    exception when trying to release an unlocked lock if it's initialized with
    strict=True.
    """

    def __init__(self, strict=False, blocking=True):
        self.__strict = strict
        self.__blocking = blocking
        self.__lock = Lock()

    def acquire(self):
        self.__lock.acquire(self.__blocking)

    def release(self):
        try:
            self.__lock.release()
        except ThreadError:
            if self.__strict:
                raise

    def locked(self):
        return self.__lock.locked()

    def __enter__(self, *args):
        self.acquire()

    def __exit__(self, *args):
        self.release()
开发者ID:nkoep,项目名称:blaplay,代码行数:32,代码来源:__init__.py

示例7: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Terminal:
    lock = None
    app = None

    def __init__(self, app):
        self.lock = Lock()
        self.lock.acquire()
        self.app = app
        self.app.debug_print = lambda cmd: eval(cmd)

    def show_terminal(self):
        if self.lock.locked():
            self.lock.release()

    def pause_terminal(self):
        if not self.lock.locked():
            self.lock.acquire()

    def run_terminal(self):
        with self.lock:
            printc("\n\nInput commands to RCAT below. Type help for list for commands.", "blue")
        while 1:
            self.lock.acquire()
            sys.stdout.write(ansi_codes["green"] + "[rcat]: ")
            line = sys.stdin.readline()
            if line.startswith("quit"):
                printc("Quitting RCAT....", "yellow")
                sys.exit(0)
            if line.startswith("help"):
                printc(
                    "quit: (Force) quits RCAT\nprint arg: Runs a 'print arg' in the application. Application represented by 'app' (e.g. print app)",
                    "endc",
                )
            if line.startswith("restart"):
                self.app.declare_game_end()
            if line.startswith("print"):
                try:
                    cmd = line.split()
                    if len(cmd) > 2:
                        logging.warn("Only one variable at a time.")
                    else:
                        app = self.app
                        print eval(cmd[1])
                except Exception, e:
                    logging.error("Could not read variable.")
                    print e
            self.show_terminal()
开发者ID:Mondego,项目名称:rcat,代码行数:49,代码来源:helper.py

示例8: Renderer

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Renderer(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.x = 0
        self.snapshot = 0
        self.param_update = Lock()
        print_(self.param_update.locked())
        self.param_ready = Lock()
        self.param_ready.acquire() # not ready
        self.ss_update = Lock() # not wanted
        self.ss_ready = Lock()
        self.ss_ready.acquire() # not ready
        self.param_lock = Lock()
        self.print_ = get_print("Rnd", Fore.YELLOW) 

    def set_param(self, x):
        self.x = x
        
    def draw(self):
        sleep_time = randint(0,5)/10.
        self.print_("drawing")
#         if self.param_update.locked():
#             # if it is updating, wait until it is ready
#             self.param_ready.acquire()
        self.param_update.acquire()
        self.print_("using param - %d" % self.x)
        sleep(sleep_time) # rendering to frame buffer
        self.snapshot = self.x # swap frame buffer
        self.print_("frame buffer - %d" % self.snapshot)
        if self.ss_update.locked():
            self.save_snapshot()
            self.ss_ready.release()
        self.param_update.release()
        sleep(0.5 - sleep_time)
    
    def save_snapshot(self):
        self.print_("saving snapshot - %d - %d"%(self.snapshot, self.x))
        
    def run(self):
        while True:
            self.draw()
开发者ID:chxzh,项目名称:shadyn,代码行数:43,代码来源:concurence_model.py

示例9: Locker

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Locker(metaclass=Singleton):
    def __init__(self):
        self.lock = Lock()

    def set_acquire(self):
        self.lock.acquire()

    def set_release(self):
        self.lock.release()

    def is_locked(self):
        return self.lock.locked()

    def printID(self):
        return id(self.lock)
开发者ID:hiyoku,项目名称:ccd10,代码行数:17,代码来源:Locker.py

示例10: SingleThread

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class SingleThread():
    def __init__(self, progressbar=None):
        self.lock = Lock()
        self.progressbar = progressbar
        
    def run_with_progressbar(self, method, args=None, text='', no_thread=False, with_lock=True):
        #with_lock - shows, does it necessarily to do a lock or not
        
        if no_thread:
            if method and args:
                method(args)
            if method:
                method()
        else:
            self._run(method, args, text, with_lock)
                
    def _run(self, method, args=None, text='', with_lock=True):
        if not self.lock.locked():            
            self.lock.acquire()
            if self.progressbar:
                self.progressbar.start(text)
            thread.start_new_thread(self._thread_task, (method, args,))
        else:
            logging.warning("Previous thread not finished " + str(method) + " " + str(args))
            if not with_lock:
                logging.info("Try to run method without progress bar")
                thread.start_new_thread(self._thread_task, (method, args))  
    
    def _thread_task(self, method, args, with_lock=True):
        try:
            if method and args:
                method(args)
            elif method:
                method()
        except Exception, e:
            logging.error(str(e))
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
        finally:
开发者ID:Andresteve07,项目名称:foobnix,代码行数:41,代码来源:single_thread.py

示例11: NaptConnection

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class NaptConnection(object):
    def __init__(self, client, server):
        Utils.expects_type(socket.socket, client, 'client')
        Utils.expects_type(socket.socket, server, 'server', True)

        self.lock           = Lock()
        self.id             = 0
        self.client         = NaptSocket(self, client, True)
        self.server         = NaptSocket(self, server, False)
        self.is_connecting  = False
        self.is_connected   = False
        self.is_closed      = False
        self.tag            = None
        self.tls            = False
        self.debug          = True
        self.bind_port      = 0

        self.connected      = Event()
        self.closed         = Event()
        self.client_closing = Event()
        self.server_closing = Event()
        self.client_closed  = Event()
        self.server_closed  = Event()
        self.client_recieved= Event()
        self.server_recieved= Event()

    def __str__(self):
        return 'NaptConnection{ %s }' % ', '.join([
            'id=%d'             % self.id,
            'client=%s'         % str(self.client),
            'server=%s'         % str(self.server),
            'is_connecting=%s'  % str(self.is_connecting),
            'is_connected=%s'   % str(self.is_connected)])

    # public
    def connect(self, endpoint):
        Utils.assertion(self.lock.locked(), 'need lock')

        if self.is_connecting:
            raise Exception() # InvalidOperationException

        self.is_connecting  = True
        self.server.status  = NaptSocketStatus.Connecting

        threading.Thread(target = self.do_connect, args = (endpoint,), name = self.__class__.__name__).start()

    # private
    def do_connect(self, endpoint):
        try:
            self.server.connect(endpoint)   # blocking

            #self.client.socket.settimeout(5.0)
            #self.server.socket.settimeout(5.0)

            with self.lock:
                if self.is_closed:
                    # todo close
                    return

                self.is_connected = True

            #print('INVOKE: on_connected')

            self.on_connected(None)
        except Exception as ex:
            print('  endpoint: %s' % str(endpoint))
            Utils.print_exception(ex)
            self.close()

    # public
    def close(self):
        with self.lock:
            #if self.is_closed:
            #    return

            self.close_client()
            self.close_server()
            self.is_closed    = True

        if self.debug:
            print('NaptConnection.close: %s' % str(self))

        self.on_closed(None)

    # protected virtual
    def on_connected(self, e):
        self.connected(self, e)

    # protected virtual
    def on_closed(self, e):
        self.closed(self, e)

    # protected virtual
    def on_client_closing(self, e):
        self.client_closing(self, e)

    # protected virtual
    def on_server_closing(self, e):
        self.server_closing(self, e)

#.........这里部分代码省略.........
开发者ID:rainforest-tokyo,项目名称:AutoNaptPython,代码行数:103,代码来源:NaptConnection.py

示例12: ConfigDialog

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class ConfigDialog(object):
	__xml = None
	__dialog = None
	__mode = 0
	__button = BUTTON_1
	MODES = [u'0', u'A', u'B', u'AB']
	__modes = []
	__buttons = []
	__actions = []
	__act = None
	__cbAct = None
	__vbActConfig = None
	__ulock = None
	def __init__(self, config):
		self.__conf = config
		self.__xml = glade.XML(resource('config.glade'))
		self.__xml.signal_autoconnect(self)
		self.__dialog = self.__xml.get_widget('gdConfig')
		self.__buttons = [self.__xml.get_widget('b%i'%(btn+1)) for btn in range(BUTTON_1, BUTTON_9+1)]
		self.__modes = [None, self.__xml.get_widget('tbModeA'), self.__xml.get_widget('tbModeB')]
		self.__actions = sorted(list(actionObjs()), (lambda a,b: cmp(a.label, b.label)))
		self.__cbAct = self.__xml.get_widget('cbAction')
		set_model_from_list(self.__cbAct, map((lambda a: a.label), self.__actions))
		self.__vbActConfig = self.__xml.get_widget('vbActConfig')
		self.__ulock = Lock()
		self.__set_action(self.__conf[self.__mode, self.__button][0])
		self.__update(True)
	
	def __name(self):
		FORMAT = u"%(num)i (%(mode)s)"
		mode = self.MODES[self.__mode]
		return FORMAT % {'mode': mode, 'num': self.__button + 1}
	
	def __set_action(self, action):
		if self.__act is not None:
			for name, label, conf in self.__act.config:
				conf.destroy()
		if isinstance(action, int):
			i = action
			action = self.__actions[i]
		else:
			print "change", self.__actions, action
			i = self.__actions.index(action)
			self.__cbAct.set_active(i)
		self.__act = action
		self.__vbActConfig.forall(self.__vbActConfig.remove) # Get rid of previous children
		ops = self.__conf[self.__mode, self.__button][1]
		if ops is None: ops = {}
		print "load ops", ops
		for name, label, conf in action.config:
			print "nlc:", name, label, conf
			ui = conf.createInput(self.__save)
			if name in ops: 
				conf.setValue(ops[name])
			self.__vbActConfig.add(ui)
		self.__vbActConfig.show_all()
	
	def __save(self):
		if self.__ulock.locked(): return # Don't save when updating
		ops = {}
		for name, label, conf in self.__act.config:
			ops[name] = conf.getValue()
		print "Save:", self.__act, ops
		self.__conf[self.__mode, self.__button] = (self.__act, ops)
		print "saved:", self.__conf[self.__mode, self.__button]
	
	def __update(self, first=False):
		if not self.__ulock.acquire(False): return
		try:
			self.__xml.get_widget('lbldButton').set_label(self.__name())
			if bool(self.__mode & MODE_A) != bool(self.__modes[MODE_A].get_active()):
				self.__modes[MODE_A].set_active(bool(num & MODE_A))
			if bool(self.__mode & MODE_B) != bool(self.__modes[MODE_B].get_active()):
				self.__modes[MODE_B].set_active(bool(self.__mode & MODE_B))
			conf = self.__conf[self.__mode, self.__button]
			self.__set_action(conf[0] or Action())
		finally:
			self.__ulock.release()
	
	def buttonChange(self, widget, data=None):
		num = self.__buttons.index(widget)
		print "buttonChange", widget, num
		self.__save()
		if num != self.__button:
			self.__button = num
			self.__update()
	
	def modeChange(self, widget, data=None):
		num = self.__modes.index(widget)
		print "modeChange", widget, num
		self.__save()
		self.__mode = (self.__mode & ~num) | (num if widget.get_active() else 0)
		self.__update()
	
	def actionChange(self, widget, data=None):
		print "actionChange", widget, data
		i = widget.get_active()
		self.__set_action(i)
		self.__save()
	
#.........这里部分代码省略.........
开发者ID:astronouth7303,项目名称:commandpad,代码行数:103,代码来源:config.py

示例13: RSS2AlarmManager

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class RSS2AlarmManager(object):
    implements(IRSS2Document)
    adapts(IAlarmManager)
    def __new__(klass, manager):
        syndicator_name = '__' + klass.__name__
        syndicator = getattr(manager, syndicator_name, None)
        if syndicator is None:
            print 'Creating new RSS2AlarmManager'
            syndicator = super(RSS2AlarmManager, klass).__new__(klass)
            setattr(manager, syndicator_name, syndicator)
            syndicator.initialize(manager)
        return syndicator
    def initialize(self, manager):
        self.debug = 0
        self.manager = manager
        self.cache_lock = Lock()
        self.cache_ttl = 30
        self.closed_event_ttl = 3 * 60
        self.caches = {}
        self.close_events = {}
        self.event_queue = EventQueue()
        self.hostname = AlarmEvent.LOCALORIGIN
        self.uri_base = 'http://' + self.hostname
        if self.uri_base[-1] == '/':
            self.uri_base = self.uri_base[0:-1]
        self.categories = {
            'RAISED': rss.Category("Raised"),
            'INACTIVE': rss.Category("Inactive"),
            'ACCEPTED': rss.Category("Accepted"),
            'CLEARED': rss.Category("Cleared"),
            'CLOSED': rss.Category("Closed")
        }
        self.last_pub_time = None
        self.updatesub = self.manager.register_for_type(
            self.initialize_caches, FormationUpdated)
        self.subscription = self.manager.register_for_type(
            self.handle_alarm_update, StateEvent, None, True)
        self.initialize_caches()
    def initialize_caches(self, *args):
        if self.debug: tstart = time.time()
        print 'RSS2 Syndic initializing caches because: %s' % (args,)
        events = []
        self.cache_lock.acquire()
        try:
            self.event_queue.popqueue()
            for group in map(Alarm.get_events, self.manager.get_alarms()):
                events.extend(group)
            events.extend(self.manager.get_remote_events())
            events.extend(self.event_queue.popqueue())
            self.caches = {None: ItemCache()}
            cache = self.process_events(events)
        finally:
            self.cache_lock.release()
        if self.debug:
            tend = time.time()
            tlapse = tend - tstart
            print 'RSS2 cache init of %s events took %s seconds.' % (len(events), tlapse)
        return cache
    def process_events(self, events):
        if not self.cache_lock.locked():
            raise Exception('Process events cannot be called unless locked.')
        cache = {}
        if events: 
            guids = map(Event.get_guid, events)
            items = map(self.item_from_event, events)
            cache.update(zip(guids, items))
            for existing in self.caches.values():
                existing.update(cache)
        return cache
    def handle_alarm_update(self, event):
        if self.debug: 
            tstart = time.time()
        if isinstance(event, StateEvent):
            event = event.source
        if event.is_state('closed'):
            self.close_events[event.GUID] = uptime.secs()
        self.event_queue.enqueue(event)
        if self.cache_lock.acquire(0):
            try:
                self.trim_expired_caches()
                self.process_events(self.event_queue.popqueue())
            finally: 
                self.cache_lock.release()
        else: 
            print 'Alarm update not processing queue; locked.'
        if self.debug:
            tend = time.time()
            tlapse = tend - tstart
            print 'Took RSS2 Syndic %s secs to handle alarm event.' % tlapse
        return
    def render(self, request_path = None, cache_id = None):
        if request_path is None:
            request_path = '/syndication'
        xmldoc = self.setup_xmldoc()
        channel = self.setup_channel(request_path)
        xmldoc.root_element.channel = channel
        self.cache_lock.acquire()
        try:
            self.trim_expired_caches()
            queue = self.event_queue.popqueue()
#.........这里部分代码省略.........
开发者ID:mcruse,项目名称:monotone,代码行数:103,代码来源:adapters.py

示例14: __init__

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class Downloader:

    def __init__(self, url, dlhash, rawserver, failed_func, max_errors = 10):
        if DEBUG:
            log('dd-downloader::__init__: url', url, 'hash', binascii.hexlify(dlhash))
        self.url = url
        self.rawserver = rawserver
        self.failed_func = failed_func
        self.final_url = None
        self.storage = None
        self.lock = Lock()
        self.measure = Measure(10.0)
        self.errors = 0
        self.max_errors = max_errors
        self.seek = None
        self.shutdown_flag = False
        self.running = False
        self.log_prefix = 'dd-downloader::' + binascii.hexlify(dlhash) + ':'

    def predownload(self, callback, timeout = 10):
        if self.lock.locked():
            self.seek = pos
            return
        t = Thread(target=self._predownload, args=[callback, timeout])
        t.setName('dd-downloader-predownload-' + t.getName())
        t.setDaemon(True)
        t.start()

    def _predownload(self, callback, timeout):
        self.lock.acquire()
        self.running = True
        try:
            if DEBUG:
                log(self.log_prefix + '_predownload: url', self.url, 'timeout', timeout)
            stream = urlOpenTimeout(self.url, timeout=timeout)
            content_type = stream.info().getheader('Content-Type')
            content_length = stream.info().getheader('Content-Length')
            if DEBUG:
                log(self.log_prefix + '_predownload: request finished: content_type', content_type, 'content_length', content_length)
            data = ''
            while True:
                if self.shutdown_flag:
                    if DEBUG:
                        log(self.log_prefix + '_predownload: got shutdown flag while reading: url', self.url)
                    break
                buf = stream.read(524288)
                if not buf:
                    if DEBUG:
                        log(self.log_prefix + '_predownload: eof: url', self.url)
                    break
                data += buf
                if DEBUG:
                    log(self.log_prefix + '_predownload: read chunk: url', self.url, 'read_len', len(data))

            stream.close()
            if not self.shutdown_flag:
                if DEBUG:
                    log(self.log_prefix + '_predownload: finished, run callback: url', self.url, 'content_type', content_type, 'content_length', content_length, 'data_len', len(data))
                callback(content_type, data)
        except Exception as e:
            if DEBUG:
                print_exc()
            self.failed_func(e)
        finally:
            self.running = False
            self.lock.release()

    def init(self, callback = None, timeout = 10):
        if callback is None:
            return self._init()
        t = Thread(target=self._init, args=[callback, timeout])
        t.setName('dd-downloader-init-' + t.getName())
        t.setDaemon(True)
        t.start()

    def _init(self, callback = None, timeout = 10):
        try:
            scheme, host, path = self.parse_url(self.url)
            redirects = 0
            connection = HTTPConnection(host)
            while True:
                connection.request('HEAD', path, None, {'Host': host,
                 'User-Agent': USER_AGENT})
                r = connection.getresponse()
                if r.status == 200:
                    break
                elif r.status == 301 or r.status == 302:
                    redirect_url = r.getheader('Location', None)
                    if DEBUG:
                        log(self.log_prefix + 'init: got redirect: url', self.url, 'redirect', redirect_url)
                    scheme, rhost, path = self.parse_url(redirect_url)
                    redirects += 1
                    if redirects > MAX_REDIRECTS:
                        raise Exception('Too much redirects')
                    if rhost != host:
                        connection.close()
                        connection = HTTPConnection(rhost)
                        host = rhost
                else:
                    raise Exception('Bad http status: ' + str(r.status))
#.........这里部分代码省略.........
开发者ID:2jangelman,项目名称:P2P-Streams-XBMC--Modules-,代码行数:103,代码来源:Downloader.py

示例15: SQL_Panel

# 需要导入模块: from threading import Lock [as 别名]
# 或者: from threading.Lock import locked [as 别名]
class SQL_Panel(ScrollView):
    '''
    The logback panel is used to turn logs on and off as well as adjust the error level of each one
    and the default error level.
    '''
    grid = ObjectProperty(None)
    active = BooleanProperty(False)
    query = "Select * from logs where parent in (select parent from logs where line like '%org.hibernate.SQL%') ORDER BY parent"
    get_parents = "select parent from logs where line like '%org.hibernate.SQL%'"
    get_exclusive_parents = "select parent from logs where line like '%org.hibernate.SQL%' and parent not in ({0})"
    parent_query = "Select * from logs where parent is {0}"
    def setServer(self,server):
        '''
        Save the local variables needed. Server specifically, but also this method spins up an
        instance of the Logback model to reference.
        '''
        self.server = server
        self.logback = model.LogbackFile(server.con)
        loggers = self.logback.getLoggers()
        self.loggers = []

        for i in loggers:
            if i.name == 'org.hibernate.SQL':
                self.ohsql = i
            if i.name == 'org.hibernate.type':
                self.ohtype = i

        self.active = not (self.ohsql.commented and self.ohtype.commented)

        self.load_queries()
        self.bind(on_touch_down=self.on_touch_down)

    def load_queries(self):
        self.logFile = model.gstore.logManager.openLog(
            '/usr/local/tomcat/logs/portal/portal.log',self.server.con)

        self.query_list_hashes = []
        self.query_list = {}
        self.query_nodes = {}
        self.updating = Lock()
        self.parents = []
        
        Clock.schedule_interval(self.thread_update,1)

    def thread_update(self,*args):
        Logger.debug("SQL Panel: Is there a running updater thread? {0}".format(self.updating.locked()))
        if self.updating.locked() == False:
            Logger.debug("SQL Panel: Preparing a new thread")
            t = Thread(target=self.update,args=args)
            t.start()
            Logger.debug("SQL Panel: Dispached thread")
        Logger.debug("SQL Panel: Done checking the updater.")
        

    def update(self, *args):
        #this makes sure only one update process is running at a time.
        Logger.debug("SQL Panel: Is an update process alread running?: {0}".format(self.updating.locked()))
        if self.updating.acquire(False) == False:
            Logger.debug("SQL Panel: Lock not acquired: {0}".format(self.updating.locked()))
            return
        Logger.debug("SQL Panel: Acquired lock:".format(self.updating.locked()))
        
        #Get the list of parents into a string form.
        p_list = ','.join([str(i) for i in self.parents])

        #query for the queries we don't already have
        parents = self.logFile.query(self.get_exclusive_parents.format(p_list))

        #save those to the raw parents list. May get ride of this later.
        self.parents_raw = parents

        #Process the new queries:
        for p in parents:
            self.parents.append(p[0])
            qhash, query = self.process_query(p[0])
            
            if qhash in self.query_list_hashes:
                #self.query_list[qhash].ids.append(p[0])
                self.query_list[qhash].add_instance(p[0])
                
            else:
                self.query_list_hashes.append(qhash)
                self.query_list[qhash] = SQL_Query(qhash,query,p[0],self)

        self.updating.release()
        Logger.debug("SQL Panel: Done updating, toggling self.update to: {0}".format(self.updating.locked()))

    def process_query(self,parent):
        '''
        Take the given number, find all the parts of the query, and then string them together into
        one piece. This also returns the hash for that query to make use in dictionaries easier.
        '''
        query_raw = self.logFile.query(self.parent_query.format(parent))
        query = ''
        query = '\n'.join([i[2] for i in query_raw[1:]])

        q_hash = hash(query)
        return (q_hash,query)

    def get_from(self,query):
#.........这里部分代码省略.........
开发者ID:Narcolapser,项目名称:bookish-octo-computing-machine,代码行数:103,代码来源:sql_panel.py


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