在本例子之中,多线程的实现是通过继承threading.Thread,
在类中定义stop函数,在需要杀死该线程时进行杀死
定义类的代码如下:
class socketCreateStoppable(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self,server_ip, server_port,macNumA,macNumB,distanceListA,distanceListB,timestrapListA,timestrapListB):
# 这些类内变量有些是可迭代的对象,此时在类内修改了这些变量,在全局中也是修改了的
super(socketCreateStoppable, self).__init__()
self._stop_event = threading.Event()
self.server_ip = server_ip
self.server_port = server_port
self.macNumA = macNumA
self.macNumB = macNumB
self.distanceListA = distanceListA
self.distanceListB = distanceListB
self.timestrapListA = timestrapListA
self.timestrapListB = timestrapListB
# 定义stop方法
def stop(self):
print(time.time())
print('#'*20)
self._stop_event.set()
print(time.time(),'stop success')
# 定义键值,通过查询该值确定是否停了
def stopped(self):
return self._stop_event.is_set()
def run(self):
print("begin run the child thread")
tcp_client = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
# server_ip = '192.168.0.120'
# server_port = 5026
while True:
try:
tcp_client.settimeout(10)
tcp_client.connect((self.server_ip, self.server_port))
print('server_ip:', self.server_ip)
while True:
# 3.收发
recv_content = tcp_client.recv(1024)
#print(recv_content)
self.dataList = list(recv_content)
#check_struct(dataList, self.macNumA, self.macNumB, distanceListA, distanceListB, timestrapListA, timestrapListB)
self.check_struct()
except Exception as e:
print(e)
time.sleep(5)
print("sleep 1s")
time.sleep(1)
# 查询是否被杀死了,如果被杀死就进行相关的扫尾工作
if self.stopped():
# 做一些必要的收尾工作
tcp_client.close()
break
def check_struct(self):
# numA代表A的mac码 numB代表B的mac码
# distanceListA与B分别代表当前基站与距离AB标签的距离
# timestrapList代表是写AB时的时间戳,如果有某一个时间戳不更新了,会给其赋值一个很大的数
if len(self.dataList) == 23:
if self.dataList[0] == 170 and self.dataList[2] == 17 and self.dataList[-1] == 126:
macList = self.dataList[3:9]
length = (self.dataList[18] * 256 + self.dataList[19]) * 0.01
if macList == self.macNumA:
self.distanceListA.append(length)
self.timestrapListA.append(time.time())
elif macList == self.macNumB:
self.distanceListB.append(length)
self.timestrapListB.append(time.time())
else:
print('mac is error')
else:
print('information error')
else:
print('information error')