Python 2.7
这是我的代码。你能告诉我什么是错的。这是我连续两天研究穿线后想出来的野兽。
当我不使用线程时,串行通信工作。
main()
答案 0 :(得分:2)
您没有正确同步线程。我建议将ser
对象放入全局命名空间并使用锁,互斥锁或信号量来防止两个线程同时访问单个ser
对象。
本周的Python模块最好地解释了here
答案 1 :(得分:0)
使用锁的示例
import threading
import time
import sys
import serial
import os
import time
def Task1(lck,ser):
while 1:
print "Inside Thread 1"
lck.acquire()
ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit
b = ser.read(7)
lck.release()
print b.encode('hex')
print "Thread 1 still going on"
time.sleep(1)
def Task2(lck,ser):
print "Inside Thread 2"
print "I stopped Task 1 to start and execute Thread 2"
lck.acquire()
ser.write('x5A\x03\x02\x08\x02\x0F')
c = ser.read(7)
lck.release()
print c.encode('hex')
print "Thread 2 complete"
def Main():
ser = serial.Serial(3, 11520)
lck = threading.Lock()
t1 = threading.Thread(target = Task1, args=[ser,lck])
t2 = threading.Thread(target = Task2, args=[ser,lck])
print "Starting Thread 1"
t1.start()
print "Starting Thread 2"
t2.start()
print "=== exiting ==="
ser.close()
if __name__ == '__main__':
Main()