Created
March 30, 2017 10:53
-
-
Save leafsummer/90671d13f92999bdbd70bfe80d032b7a to your computer and use it in GitHub Desktop.
singleton bus for the thread running
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#encoding=utf8 | |
import threading | |
import time | |
#这里使用方法__new__来实现单例模式 | |
class Singleton(object):#抽象单例 | |
def __new__(cls, *args, **kw): | |
if not hasattr(cls, '_instance'): | |
orig = super(Singleton, cls) | |
cls._instance = orig.__new__(cls, *args, **kw) | |
return cls._instance | |
#总线 | |
class Bus(Singleton): | |
lock = threading.RLock() | |
def sendData(self,data): | |
self.lock.acquire() | |
time.sleep(3) | |
print "Sending Signal Data...",data | |
self.lock.release() | |
#线程对象,为更加说明单例的含义,这里将Bus对象实例化写在了run里 | |
class VisitEntity(threading.Thread): | |
my_bus="" | |
name="" | |
def getName(self): | |
return self.name | |
def setName(self, name): | |
self.name=name | |
def run(self): | |
self.my_bus=Bus() | |
self.my_bus.sendData(self.name) | |
if __name__=="__main__": | |
for i in range(3): | |
print "Entity %d begin to run..."%i | |
my_entity=VisitEntity() | |
my_entity.setName("Entity_"+str(i)) | |
my_entity.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment