我正在使用类似的代码来控制rgb led条带,每隔几秒就会出现一次随机值,并且正在创建3个线程来控制3种颜色。
import time
from ast import literal_eval
import threading
from random import randint
t=[]
myR =0
myG =0
myB =0
temp = 0
pins = [17,22,24]
myColours = [myR,myG,myB]
red_pin = 17
green_pin = 22
blue_pin = 24
def change_led_color(rgb):
global myR
global myG
global myB
y = 0
threads = []
for colour in rgb:
t = threading.Thread(target=leds,name=pins[y] ,args=(y,myColours[y],colour,pins[y]))
threads.append(t)
y += 1
for y in threads:
y.start()
for y in threads:
y.join()
def leds(index,start,end,pin):
temp=0
for i in range(start,end):
time.sleep(0.01)
temp = i
global myColours
print 'pin', pin, 'started at: ',start,' ended is: ', temp
myColours[index] = end
def set_colours():
print '..................................................................',t
print threading.activeCount(),'threads \n'
threading.Timer(2, set_colours).start()
change_led_color(t)
set_colours()
def get_data():
while True:
global t
t = (randint(0,255),randint(0,255),randint(0,255))
time.sleep(2)
threading.Thread(target=get_data).start()
以上运行正常,但响应非常奇怪,而不是在线程末尾获得所有三种颜色,我有时会得到超过预期的大多数时间至少有一个将是0,就像线程永远不会跑! 我假设我在某种程度上误用了线程......
e.g。结果
.................................................................. (187, 223, 42)
3 threads
pin 24 started at: 205 ended is: 0
pin 22 started at: 170 ended is: 222
pin 17 started at: 107 ended is: 186
.................................................................. (202, 115, 219)
3 threads
pin 22 started at: 223 ended is: 0
pin 17 started at: 187 ended is: 201
.................................................................. (244, 35, 194)
5 threads
pin 22 started at: 115 ended is: 0
pin 24 started at: 42 ended is: 218
pin 17 started at: 202 ended is: 243
pin 24 started at: 42 ended is: 193
.................................................................. (54, 25, 72)
3 threads
pin 17 started at: 244 ended is: 0
pin 22 started at: 35 ended is: 0
pin 24 started at: 194 ended is: 0
答案 0 :(得分:1)
您是否考虑过GIL(Global Interpreter lock)? https://wiki.python.org/moin/GlobalInterpreterLock
Python有一个GIL,它不允许多个线程从单个进程运行。运行代码时,它将作为python进程运行。您正在尝试从python中不允许的同一进程启动线程。
如果您想并行执行某些操作,多处理包是一个不错的选择 https://pymotw.com/2/multiprocessing/basics.html
答案 1 :(得分:1)
如果不考虑其他因素(见下文),for i in range(start,end):
循环将持续长达2.5秒;但实际上你每2秒产生一次新线程。
此外,该循环的实际持续时间实际上甚至更长:
for i in range(start,end):
中花费的总时间将超过预期尝试:
time.sleep(0.01 * start-end if end>start else 0)