加入后Python线程没有关闭

时间:2016-11-29 15:19:26

标签: python multithreading python-multithreading

我正在使用类似的代码来控制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

2 个答案:

答案 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秒产生一次新线程。

此外,该循环的实际持续时间实际上甚至更长:

  • 每当你要求睡觉时,持续时间至少是你所要求的;但它可能稍微多一些。特别是当你要求1/100秒时,它可能会长一点。
  • 由于你要求一个接一个地进行许多小睡眠,你可能会认为效果会成倍增加;意味着在循环for i in range(start,end):中花费的总时间将超过预期

尝试:

  • 使用一次等待:time.sleep(0.01 * start-end if end>start else 0)
  • 将用于生成新主题的时间增加到3-4秒