Python多线程实例

特别注意:
加锁的位置一定要只包住临界资源,如:
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值