一、首先对python的学习
Python中使用线程有两种方式:函数或者用类来包装线程对象。
1.1函数式的线程调用
函数式:调用thread模块中的start_new_thread()函数来产生新线程。代码如下:
import time
import thread
def timer(no, interval):
cnt = 0
while cnt < 10:
print('Thread:(%d) Time:%s\n' % (no, time.ctime())) #用于测试
time.sleep(interval)
cnt += 1
thread.exit_thread()
def test(): # 创建新的线程
thread.start_new_thread(timer, (1, 1))
thread.start_new_thread(timer, (2, 2))
if __name__ == '__main__':
test()
上面的例子定义了一个线程函数timer,它打印出10条时间记录后退出,每次打印的间隔由interval参数决定。thread.start_new_thread(function, args[, kwargs])的第一个参数是线程函数(本例中的timer方法),第二个参数是传递给线程函数的参数,它必须是tuple类型,kwargs是可选参数。线程的结束可以等待线程自然结束,也可以在线程函数中调用thread.exit()或thread.exit_thread()方法。
threading.Thread的子类
创建threading.Thread的子类来包装一个线程对象,代码如下:
"""
2019/7/28 :test threading
"""
# E:\Anaconda3\python.exe
# -*- coding: utf-8 -*-
import threading
import time
class timer(threading.Thread): # The timer class is derived from the class threading.Thread
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = interval
self.thread_stop = False
def run(self): # Overwrite run() method, put what you want the thread do here
while not self.thread_stop:
print('Thread Object(%d), Time:%s\n' % (self.thread_num, time.ctime()))
time.sleep(self.interval)
def stop(self):
self.thread_stop = True
def test():
thread1 = timer(1, 1)
thread2 = timer(2, 2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
return
if __name__ == '__main__':
test()
执行结果:
可以看出线程在异步运行(后期可以了解GIL)
相比较而言,喜欢第二种方式,即创建自己的线程类,必要时重写threading.Thread类的方法,线程的控制可以由自己定制。
threading.Thread类的使用:
1,在自己的线程类的__init__里调用threading.Thread.init(self, name = threadname)
Threadname为线程的名字
2, run(),通常需要重写,编写代码实现做需要的功能。
3,getName(),获得线程对象名称
4,setName(),设置线程对象名称
5,start(),启动线程
6,jion([timeout]),等待另一线程结束后再运行。
7,setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
8,isDaemon(),判断线程是否随主线程一起结束。
9,isAlive(),检查线程是否在运行中。
此外threading模块本身也提供了很多方法和其他的类,可以帮助我们更好的使用和管理线程。可以参看http://www.python.org/doc/2.5.2/lib/module-threading.html。
**python里提供了多个用于控制多线程同步的同步原语,这些原语,包含在python的标准库threading.py当中。python里的这些控制多线程同步的原语,包括:Locks、RLocks、Semaphores、Events、Conditions和Barriers,你也可以继承这些类,实现自己的同步控制原语。**后期我们要加上。
二、选装编码器线程测试
首先对单个旋转编码器测试,测试代码如下:
# E:\Anaconda3\python.exe
# -*- coding: utf-8 -*-
import serial
import numpy as np
import threading
array_one = np.ones([648, 1])
flagExit = 0
def dev_init():
global encode_serial
encode_serial = serial.Serial(port="COM7", baudrate=115200, timeout=0.5)
print("init ")
def endcode_get_data():
global flagExit, encode_serial
print('endcode_get_data')
#encode_serial.flushInput()
while 1:
count = serial.Serial.inWaiting(encode_serial)
if count >0:
line = encode_serial.readline()
line = line.strip()
str_line = line.decode('utf-8')
print(str_line)
if flagExit == 1:
encode_serial.flushInput()
encode_serial.close()
break
def main():
global encode_serial
t_encode = threading.Thread(target=endcode_get_data, name='encodeThread')
print('thread %s is running.' % threading.current_thread().name)
t_encode.start()
t_encode.join()
print('thread %s ended.' % threading.current_thread().name)
if __name__ == '__main__':
dev_init()
main()
执行结果:
三、激光雷线程调试
具体代码如下:
"""
2019/7/24 :test LIDAR_data and serial get encode
"""
import time
import serial
import os,sys
import hokuyo
import serial_port
import threading
import pandas as pd
import numpy as np
flagExit = 0
def dev_init():
global laser, laser_serial, encode_serial, f_Lidar, f_Arduino
laser_serial = serial.Serial(port="COM14", baudrate=115200, timeout=1)
port = serial_port.SerialPort(laser_serial)
laser = hokuyo.Hokuyo(port)
encode_serial = serial.Serial(port="COM7", baudrate=115200, timeout=0.5)
startTime = time.strftime('%m%d%H%M')
os.mkdir('./%s' % startTime)
filename_Lidar = './%s/dataFromLidar' % startTime
filename_Arduino = './%s/dataFromArduino' % startTime
f_Lidar = open(filename_Lidar, 'w')
f_Arduino = open(filename_Arduino, 'w')
lidar_start()
print("init ")
def endcode_get_data():
global flagExit, encode_serial, f_Arduino
print('endcode_get_data')
def lidar_start():
print('laser_on(): ')
print(laser.laser_on())
def lidar_end():
print('laser.laser_off()')
print(laser.laser_off())
def lidar_get_data():
dict1 = laser.get_single_scan()
dict1 = laser.get_single_scan()
dict2 = pd.DataFrame(pd.Series(dict1), columns=['distance'])
dict2 = dict2.reset_index().rename(columns={'index': 'angle'})
print(dict2.head(648))
f_Lidar.write("dict1")
def main():
global laser, laser_serial, encode_serial, f_Lidar, f_Arduino
t_encode = threading.Thread(target=endcode_get_data, name='encodeThread')
t_lidar = threading.Thread(target=lidar_get_data, name='lidarThread')
print('thread %s is running.' % threading.current_thread().name)
t_encode.start()
t_lidar.start()
t_encode.join()
t_lidar.join()
print('thread %s ended.' % threading.current_thread().name)
if __name__ == '__main__':
dev_init()
while 1:
main()
执行结果:
四、两者结合测试
代码如下:
"""
2019/7/24 :test LIDAR_data and serial get encode
"""
import time
import serial
import os,sys
import hokuyo
import serial_port
import threading
import pandas as pd
import numpy as np
flagExit = 0
def dev_init():
global laser, laser_serial, encode_serial, f_Lidar, f_Arduino
laser_serial = serial.Serial(port="COM14", baudrate=115200, timeout=1)
port = serial_port.SerialPort(laser_serial)
laser = hokuyo.Hokuyo(port)
encode_serial = serial.Serial(port="COM7", baudrate=115200, timeout=0.5)
startTime = time.strftime('%m%d%H%M')
os.mkdir('./%s' % startTime)
filename_Lidar = './%s/dataFromLidar' % startTime
filename_Arduino = './%s/dataFromArduino' % startTime
f_Lidar = open(filename_Lidar, 'w')
f_Arduino = open(filename_Arduino, 'w')
lidar_start()
print("init ")
def endcode_get_data():
global flagExit, encode_serial, f_Arduino
print('endcode_get_data')
#encode_serial.flushInput()
while 1:
count = serial.Serial.inWaiting(encode_serial)
if count >0:
line = encode_serial.readline()
line = line.strip()
str_line = line.decode('utf-8')
print(str_line)
f_Arduino.write('%s\n'%str_line)
time.sleep(1)
flagExit = 1
if flagExit == 1:
encode_serial.flushInput()
encode_serial.close()
f_Arduino.close()
break
def lidar_start():
print('laser_on(): ')
print(laser.laser_on())
def lidar_end():
print('laser.laser_off()')
print(laser.laser_off())
def lidar_get_data():
dict1 = laser.get_single_scan()
dict1 = laser.get_single_scan()
dict2 = pd.DataFrame(pd.Series(dict1), columns=['distance'])
dict2 = dict2.reset_index().rename(columns={'index': 'angle'})
print(dict2.head(648))
f_Lidar.write("dict1")
def main():
global laser, laser_serial, encode_serial, f_Lidar, f_Arduino
t_encode = threading.Thread(target=endcode_get_data, name='encodeThread')
t_lidar = threading.Thread(target=lidar_get_data, name='lidarThread')
print('thread %s is running.' % threading.current_thread().name)
t_encode.start()
t_lidar.start()
t_encode.join()
t_lidar.join()
print('thread %s ended.' % threading.current_thread().name)
if __name__ == '__main__':
dev_init()
while 1:
main()
执行结果:出现错误提示
总结
有人说是串口的冲突,也有人说是线程同步问题…具体问题我也不知道,后期检查问题所在。