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


Python QMutex.lock方法代码示例

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


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

示例1: QtStreamHandler

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class QtStreamHandler(logging.Handler): 
    def __init__(self, parent, main): 
        logging.Handler.__init__(self) 
        self.parent = parent 
        self.main = main         
        self.textWidget = parent 
        self.formater = logging.Formatter("%(asctime)s - %(levelname)s -> %(message)s") 
        self.logString = ""
    def getLoggingCompleteText(self):
        return self.logString
    def createLock(self): 
        self.mutex = QMutex() 
    
    def acquire(self): 
        self.mutex.lock() 
    
    def release(self): 
        self.mutex.unlock() 
    
    def emit(self, record): 
#        self.textWidget.appendPlainText(self.formater.format(record))
        formattedText = self.formater.format(record)
        #separate text from date
        index = formattedText.find('->')
        self.textWidget.setTextColor(QColor("green"))
        self.textWidget.insertPlainText(formattedText[:index])
        self.textWidget.setTextColor(QColor("blue"))
        self.textWidget.insertPlainText(formattedText[index:] + "\n") 
        self.textWidget.moveCursor(QTextCursor.EndOfLine) 
        self.textWidget.ensureCursorVisible() 
        self.logString += formattedText + "\n";
开发者ID:rahulsinha20,项目名称:py-youtube-downloader,代码行数:33,代码来源:CustomLoggingHandler.py

示例2: Feed

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class Feed(QRunnable):
    def __init__(self, label, parent=None):
        QRunnable.__init__(self)
        self.label = label
        self.parent = parent
        self.data = None
        self.mutex = QMutex()
        self.setAutoDelete(True)

    def run(self):
        self.check()

    def check(self):
        try:
            self.fetch()
        except (urllib2.URLError, urllib2.HTTPError) as err:
            self.parent.error.emit(str(err))
        else:
            self.read()
            if self.data:
                self.parse()

    def fetch(self):
        auth_handler = urllib2.HTTPBasicAuthHandler()
        auth_handler.add_password(REALM, HOST,
                self.parent.user, self.parent.passwd)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)
        url = "%s/%s" % (URL_ATOM, self.label) if self.label else URL_ATOM
        self.conn = urllib2.urlopen(url)

    def read(self):
        code = self.conn.getcode()
        if code != 200:
            self.conn.close()
            self.parent.error.emit("HTTP Error %d: %s" % (
                code, BaseHTTPRequestHandler.responses[code]))
        else:
            self.data = self.conn.read()
            self.conn.close()

    def parse(self):
        tree = et.fromstring(self.data)
        for e in tree.findall("%sentry" % XMLNS):
            entry = Entry()
            entry.title = e.find("%stitle" % XMLNS).text
            entry.summary = e.find("%ssummary" % XMLNS).text
            entry.link = e.find("%slink" % XMLNS).attrib["href"]
            entry.modified = e.find("%smodified" % XMLNS).text
            entry.issued = e.find("%sissued" % XMLNS).text
            entry.id = e.find("%sid" % XMLNS).text
            for a in e.findall("%sauthor" % XMLNS):
                entry.author_name = a.find("%sname" % XMLNS).text
                entry.author_email = a.find("%semail" % XMLNS).text

            self.mutex.lock()
            self.parent.entries.append((self.label, entry))
            self.mutex.unlock()
开发者ID:gen2brain,项目名称:gmailcheck,代码行数:60,代码来源:gmailcheck.py

示例3: QCallbacksManager

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class QCallbacksManager(QObject):
    class Request(object):
        def __init__(self):
            self.event = Event()
            self.answer = None

        def __call__(self):
            raise NotImplementedError()

    class LoginRequest(Request):
        def __init__(self, backend_name, value):
            QCallbacksManager.Request.__init__(self)
            self.backend_name = backend_name
            self.value = value

        def __call__(self):
            password, ok = QInputDialog.getText(None,
                '%s request' % self.value.label,
                'Please enter %s for %s' % (self.value.label,
                                            self.backend_name),
                                                QLineEdit.Password)
            return password

    new_request = Signal()

    def __init__(self, weboob, parent=None):
        QObject.__init__(self, parent)
        self.weboob = weboob
        self.weboob.callbacks['login'] = self.callback(self.LoginRequest)
        self.mutex = QMutex()
        self.requests = []
        self.new_request.connect(self.do_request)

    def callback(self, klass):
        def cb(*args, **kwargs):
            return self.add_request(klass(*args, **kwargs))
        return cb

    @Slot()
    def do_request(self):
        self.mutex.lock()
        request = self.requests.pop()
        request.answer = request()
        request.event.set()
        self.mutex.unlock()

    def add_request(self, request):
        self.mutex.lock()
        self.requests.append(request)
        self.mutex.unlock()
        self.new_request.emit()
        request.event.wait()
        return request.answer
开发者ID:h4wkmoon,项目名称:weboob,代码行数:55,代码来源:qt.py

示例4: MyStreamHandler

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class MyStreamHandler(StreamHandler):
    def __init__(self):
        StreamHandler.__init__(self)

    def createLock(self):
        # must be Recursive (= reentrant)
        self._mutex = QMutex(QMutex.Recursive)

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

    def release(self):
        self._mutex.unlock()
开发者ID:AlecChou,项目名称:ldoce5viewer,代码行数:15,代码来源:error.py

示例5: VCSPluginThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class VCSPluginThread( QThread ):
    " Wrapper for the plugin thread "

    def __init__( self, plugin, parent = None ):
        QThread.__init__( self, parent )

        self.__plugin = plugin
        self.__requestQueue = deque()

        self.__stopRequest = False
        self.__lock = QMutex()
        self.__condition = QWaitCondition()
        return

    def run( self ):
        " Thread loop "
        while not self.__stopRequest:
            self.__lock.lock()
            while self.__requestQueue:
                path, flag = self.__requestQueue.pop()
                self.__lock.unlock()
                time.sleep( 0.01 )
                self.__processRequest( path, flag )
                if self.__stopRequest:
                    break
                self.__lock.lock()
            if self.__stopRequest:
                self.__lock.unlock()
                break
            self.__condition.wait( self.__lock )
            self.__lock.unlock()
        return

    def __processRequest( self, path, flag ):
        " Processes a single request. It must be exception safe. "
        try:
            statuses = self.__plugin.getObject().getStatus( path, flag )
            for status in statuses:
                if len( status ) == 3:
                    self.emit( SIGNAL( "VCSStatus" ), path + status[ 0 ],
                               status[ 1 ], status[ 2 ] )
                else:
                    self.emit( SIGNAL( "VCSStatus" ), path, IND_VCS_ERROR,
                               "The " + self.__plugin.getName() + " plugin "
                               "does not follow the getStatus() interface "
                               "agreement" )
        except Exception, exc:
            self.emit( SIGNAL( "VCSStatus" ), path, IND_VCS_ERROR,
                       "Exception in " + self.__plugin.getName() +
                       " plugin while retrieving VCS status: " + str( exc ) )
        except:
开发者ID:eaglexmw,项目名称:codimension,代码行数:53,代码来源:vcspluginthread.py

示例6: Lock

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class Lock(object):

    def __init__(self):
        self._mutex = QMutex()

    def __enter__(self):
        self._mutex.lock()

    def __exit__(self, type, value, tb):
        self._mutex.unlock()

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

    def release(self):
        self._mutex.unlock()
开发者ID:caetanus,项目名称:pygel,代码行数:18,代码来源:qt4_reactor.py

示例7: Evaluate

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class Evaluate(QThread):
    """Thread used to insolate calculation process in entities (stream, project
    and equipment, so gui can response while calculation is in process"""
    def __init__(self, parent=None):
        super(Evaluate, self).__init__(parent)
        self.mutex = QMutex()

    def start(self, entity, kwargs):
        self.entity = entity
        self.kwargs = kwargs
        QThread.start(self)

    def run(self):
        self.mutex.lock()
        self.entity(**self.kwargs)
        self.mutex.unlock()
开发者ID:edusegzy,项目名称:pychemqt,代码行数:18,代码来源:thread.py

示例8: SQLRenderThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class SQLRenderThread(CachedRenderThread):
    """
    RenderThread extending the UniqueMethodRenderThread by supplying a cancel
    method for classes with database access. The database object needs to be
    given either on the object as .db subobject or explicitly by
    setObjectDBObject().
    The database object needs to have a 'connection' attribute which supports an
    interrupt() method.
    """
    def __init__(self, parent=0):
        self.dbObjectLock = QMutex(QMutex.Recursive)
        self.dbObject = {}
        CachedRenderThread.__init__(self, parent)

    def setObject(self, classObject, *args, **param):
        self.dbObjectLock.lock()
        if classObject in self.dbObject:
            del self.dbObject[classObject]
        self.dbObjectLock.unlock()
        CachedRenderThread.setObject(self, classObject, *args, **param)

    def setObjectDBObject(self, classObject, db):
        self.dbObjectLock.lock()
        self.dbObject[classObject] = db
        self.dbObjectLock.unlock()

    def cancelCurrentJob(self):
        QMutexLocker(self.renderingLock)
        if self.currentlyRenderingJob:
            _, classObject, _, _, _ = self.currentlyRenderingJob
            try:
                QMutexLocker(self.dbObjectLock)
                if classObject in self.dbObject:
                    db = self.dbObject[classObject]
                else:
                    classObjectInst = self.getObjectInstance(classObject)
                    if hasattr(classObjectInst, 'db'):
                        db = classObjectInst.db
                    else:
                        return False

                self.clearCurrentJob()
                db.connection.interrupt()
                return True
            except KeyError:
                return False
开发者ID:cburgmer,项目名称:eclectus,代码行数:48,代码来源:renderthread.py

示例9: UdpClient

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class UdpClient(QThread):
	def __init__(self, parent):
		QThread.__init__(self, parent)

		self.prnt = parent
		self.udp = QUdpSocket()
		addr = QHostAddress(QHostAddress.Any)
		print 'bind to:', addr.toString()
		self.udp.bind(addr, 34001)
		self.udp.error.connect(self.errorAnalyser)
		self.udp.readyRead.connect(self.readUdp)
		print "Binding..."
		self.STOP = False
		self.locker = QMutex()

	def run(self):
		self.prnt.initAvahiService()
		while True :
			if self.udp is not None and self.udp.state() == QAbstractSocket.ConnectedState :
				self.udp.waitForReadyRead()
			else : self.msleep(100)
			if self.STOP and self.udp is not None: self.udp.close(); break
		print 'UDPClient closed...'
		self.prnt.changeConnectState.emit()

	def stop(self):
		self.locker.lock()
		self.STOP = True
		self.locker.unlock()

	def readUdp(self):
		while ( self.udp.hasPendingDatagrams() ):
			data = QByteArray()
			addr = QHostAddress()
			port = 0
			try :
				datagramSize = self.udp.pendingDatagramSize()
				if datagramSize > 0 :
					(data, addr, port) = self.udp.readDatagram(datagramSize)
					#print "Datagram: [%s] from %s:%i" % (QString().fromUtf8(data), addr.toString(), port)
					self.prnt.contactMessage.emit(QString().fromUtf8(data), addr.toString())
			except socket.error, err :
				print '[in readUdp() UdpClient] SocketError1 : ', err
			except socket.timeout, err :
				print '[in readUdp() UdpClient] SocketError2 : ', err
			except :
开发者ID:F1ash,项目名称:LightMight,代码行数:48,代码来源:UdpClient.py

示例10: ComputationThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class ComputationThread(QThread):
   def __init__(self, animation_thread):
      QThread.__init__(self) 
      self.is_running =  True
      self.mutex = QMutex()
      self.other_thread = animation_thread

   def stop(self):
      self.is_running = False

   def run(self):
      while  self.is_running:
         self.mutex.lock() # locking may not be necessary
         raw_input("")
         #self.other_thread.stop( )
         self.mutex.unlock()
      print " run method ends "
开发者ID:sfgorky,项目名称:bouncing_ball,代码行数:19,代码来源:BouncingBalls.py

示例11: ImageTile

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class ImageTile(object):
    def __init__(self, rect):
        self._mutex = QMutex()
        self.image  = QImage(rect.width(), rect.height(), 
                             QImage.Format_ARGB32_Premultiplied)
        self.image.fill(0)

        self._topLeft = rect.topLeft()

        #Whenever the underlying data changes, the data version is incremented.
        #By comparing the data version to the image and request version, it can
        #be determined if the content of this tile is recent or needs to be
        #re-computed.
        
        #version of the data
        self.dataVer = 0
        
        #version of self.image
        #
        #If self.imgVer < self.dataVer, the image needs to be re-computed
        #from the new data.
        self.imgVer  = -1
        
        #version of the request that has been generated to update the contents
        #of self.image
        #
        #If self.reqVer == self.dataVer, a request is currently running that will
        #eventually replace self.image with the new data.
        self.reqVer  = -2
    
    def clear(self):
        self.image.fill(0)

    def paint(self, painter):
        self.lock()
        painter.drawImage(self._topLeft, self.image)
        self.unlock()

    def lock(self):
        self._mutex.lock()
    def unlock(self):
        self._mutex.unlock()
开发者ID:LimpingTwerp,项目名称:volumina,代码行数:44,代码来源:tiling.py

示例12: _LoggingMutexQt

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class _LoggingMutexQt(_LoggingMutex):
    def __init__(self, name):
        super(_LoggingMutexQt, self).__init__(name)
        from PyQt4.QtCore import QMutex
        self.mutex = QMutex()

    def currentThreadID(self):
        from PyQt4.QtCore import QThread
        return QThread.currentThreadId()
    
    def _acquire(self):
        self.mutex.lock()
        
    def _release(self):
        self.mutex.unlock()
    
    def enterMutex(self):
        self.mutex.lock()
        
    def exitMutex(self, *_args, **_kwargs):
        self.mutex.unlock()
开发者ID:hannesrauhe,项目名称:lunchinator,代码行数:23,代码来源:logging_mutex.py

示例13: AnimationThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class AnimationThread(QThread):
    def __init__(self):
        QThread.__init__(self) 
        self.is_running =  True
        self.mutex = QMutex()

    def stop(self):
        self.is_running = False

    def get_state(self):
        return self.is_running
    
    def change_state(self):
        self.is_running = not self.is_running

    def run(self):
        while  self.is_running:
            self.mutex.lock( ) # locking may not be necessary
            self.emit(SIGNAL("window_update_request" ))
            self.mutex.unlock()
            sleep( 0.005 )  
开发者ID:sfgorky,项目名称:bouncing_ball,代码行数:23,代码来源:BouncingBalls.py

示例14: SignalThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class SignalThread(QThread):
    def __init__(self, parent = None):
        QThread.__init__(self, parent)

        self.waitcond = QWaitCondition()
        self.mutex = QMutex()
        self.isstopped = False

    def trigger(self):
        """lock first to make sure the QThread is actually waiting for a signal"""
        self.mutex.lock()
        self.waitcond.wakeOne()
        self.mutex.unlock()

    def stopThread(self):
        self.mutex.lock()
        self.isstopped = True
        self.waitcond.wakeOne()
        self.mutex.unlock()

    def run(self):
        self.mutex.lock()
        while not self.isstopped:
            # just wait, and trigger every time we receive a signal
            self.waitcond.wait(self.mutex)
            if not self.isstopped:
                self.emit(SIGNAL("triggerSignal()"))
        self.mutex.unlock()
开发者ID:OLGGL,项目名称:Model,代码行数:30,代码来源:SignalThread.py

示例15: DatabaseThread

# 需要导入模块: from PyQt4.QtCore import QMutex [as 别名]
# 或者: from PyQt4.QtCore.QMutex import lock [as 别名]
class DatabaseThread(QThread):
    def __init__(self, framework, Data, parent = None):
        QThread.__init__(self, parent)
        self.framework = framework
        self.Data = Data
        self.qlock = QMutex()
        QObject.connect(self, SIGNAL('quit()'), self.quitHandler)
        QObject.connect(self, SIGNAL('started()'), self.startedHandler)
 
    def run(self):
        QObject.connect(self, SIGNAL('doConnectDb()'), self.connectDbHandler, Qt.DirectConnection)
        self.exec_()

    def close(self):
        self.qlock.lock()
        try:
            self.Data.close()
        finally:
            self.qlock.unlock()

    def quitHandler(self):
        self.Data.close()
        self.exit(0)

    def startedHandler(self):
        pass

    def connectDb(self, filename, callback):
        self.filename = filename
        self.callbackObj = callback
        QTimer.singleShot(50, self, SIGNAL('doConnectDb()'))

    def connectDbHandler(self):
        self.qlock.lock()
        try:
            self.Data.connect(self.filename)
        finally:
            self.qlock.unlock()

        self.callbackObj.emit(SIGNAL('connectDbFinished()'))
开发者ID:Averroes,项目名称:raft,代码行数:42,代码来源:DatabaseThread.py


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