特别注意:
加锁的位置一定要只包住临界资源,如:
加锁的位置一定要只包住临界资源,如:
self.stateLock.acquire()
tstate = self.state
self.stateLock.release()
class NetworkMgr(object):
'''
网络设置管理
'''
def __init__(self):
self.state = True
self.getThread = None
self.stateLock = threading.RLock()
self.sleeptime = 3
self.thdRun = False
self.start_ping_thread()
def start_ping_thread(self):
'''
开启获取网络连接的线程
'''
self.thdRun = True
self.getThread = threading.Thread(target = NetworkMgr.ping_network, kwargs = {'me':self})
self.getThread.setDaemon(True)
self.getThread.start()
def get_network_state(self):
'''
获取网络状态
返回值:
0:连接正常。-1:连接失败
'''
tstate = True
self.stateLock.acquire()
tstate = self.state
self.stateLock.release()
return tstate
@staticmethod
def ping_network(me):
'''
ping网络连接,成功将self.state置为0,失败将self.state置为-1
'''
while me.thdRun:
node = 'us.i-dong.com'
alive = 0; timeout = 1.0; ipv6 = 0; count = 4#默认ping4次
flood = 0; size = IdongPing.ICMP_DATA_STR
ret = IdongPing.pingNode(alive, timeout, ipv6, count, node, flood, size)
me.stateLock.acquire()
me.state = ret
me.stateLock.release()
sleep(me.sleeptime)