树梅派线程

#-*-coding:utf-8-*-

import socket
import threading
import time
import RPi.GPIO as GPIO
#全局变量
msg = ""
data = ""
#线程锁
mutex = threading.Lock()
changed = False

def controlCar():
GPIO.setmode(GPIO.BOARD)

GPIO.setup(36, GPIO.OUT)
GPIO.setup(38, GPIO.OUT)
GPIO.setup(40, GPIO.OUT)

global changed
while True:
if mutex.acquire(True):
if changed:
if msg == '前进':
print("head")
GPIO.output(38, GPIO.HIGH)
GPIO.output(40, GPIO.HIGH)
#time.sleep(3)
elif msg == '后退':
print("back")
pass
elif msg == '停下':
print("stop")
GPIO.output(40, GPIO.LOW)
else:
print("others")
pass

changed = False
mutex.release()


def getCommand():
global msg
global data
global changed
ip_port = ('172.20.32.2', 8080)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(ip_port)
#初始化socket
while True:
data, client_addr = server.recvfrom(256)
print "recv data:"
print data
print "\n"
#对资源执行写操作
if mutex.acquire(True):
msg = data
changed = True
mutex.release()
#多线程模块threading,该模块支持守护线程,守护线程(即daemon thread),是个服务线程,准确地来说就是服务其他的线程,这是它的作用——而其他的线程只有一种,那就是用户线程。如果把一个线程设置为守护线程,就表示这个线程是不重要的,进程退出时不需要等待这个线程执行完成。
controlCarThread = threading.Thread(target = controlCar)
getCommandThread = threading.Thread(target = getCommand)

try:
#设置为守护线程
controlCarThread.setDaemon(True)
getCommandThread.setDaemon(True)
#开启线程
controlCarThread.start()
getCommandThread.start()

controlCarThread.join()
getCommandThread.join()
except KeyboardInterrupt:
pass

GPIO.cleanup()

posted @ 2019-06-02 20:14  countryboy666  阅读(188)  评论(0编辑  收藏  举报