2013-11-16 1 views
0

Этот скрипт включает и выключает 2 реле Phidgets (www.phidgets.com). Я хотел открыть и закрыть реле в отдельных потоках. Ниже приведен скрипт, но печатает каждую нить в виде основного потока, подобного этомуПочему все мои потоки возвращены как главные?

Waiting for attach.... 
    172760 attached! 
    Phidget InterfaceKit 8/8/8 model 
    MainThread Starting 
    relay state is True 
    MainThread Exiting 
    MainThread Starting 
    relay state is True 
    MainThread Exiting 
    MainThread Starting 
    relay state is False 
    MainThread Exiting 
    MainThread Starting 
    relay state is False 
    MainThread Exiting 

Может ли кто-нибудь сказать мне, что я делаю неправильно? Заранее спасибо.

#!/usr/bin/env python 

#Basic imports 
from ctypes import * 
import sys, random, time, decimal, threading 


#Phidget specific imports 
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException 
from Phidgets.Devices.InterfaceKit import InterfaceKit 

class fidget(object): 
#Common base class for all phidgets 

    def __init__(self, device): 
     self.device = InterfaceKit() 

########################################   

    # open the interfacekit   
    def openIfkit(self): 
     try: 
      self.device.openPhidget() 
      self.device.waitForAttach(10000) 
      print("Waiting for attach....") 
      print ("%d attached!" % (self.device.getSerialNum())) 
      print ("%s model" % (self.device.getDeviceName())) 
     except PhidgetException, e: 
      print ("Phidget Exception %i: %s" % (e.code, e.detail))  
      exit(1) 

    # open the interfacekit   
    def closeIfkit(self): 
     try: 
      self.device.closePhidget() 
     except PhidgetException, e: 
      print ("Phidget Exception %i: %s" % (e.code, e.detail))  
      exit(1) 

    def relayOn(self, output): 

     # Set digital output port 0 to be on 
     print threading.currentThread().getName(), 'Starting' 
     self.device.setOutputState(output, 1) 
     time.sleep(.1) 
     print 'relay state is %s' %self.device.getOutputState(output) 
     print threading.currentThread().getName(), 'Exiting' 

    def relayOff(self, output): 
     print threading.currentThread().getName(), 'Starting' 
     self.device.setOutputState(output, 0) 
     time.sleep(.1) 
     print 'relay state is %s' %self.device.getOutputState(output) 
     print threading.currentThread().getName(), 'Exiting' 

#"This would create first object of fidgit class" 
x = fidget('ifkit') 
x.openIfkit() 


#t1 = threading.Thread(target=x.relayOn(0)) 
#t2 = threading.Thread(target=x.relayOn(1)) 
#t3 = threading.Thread(target=x.relayOff(0)) 
#t4 = threading.Thread(target=x.relayOff(1)) 

t1 = threading.Thread(target=x.relayOn, args=(0,)) 
t2 = threading.Thread(target=x.relayOff, args=(0,)) 
t3 = threading.Thread(target=x.relayOn, args=(1,)) 
t4 = threading.Thread(target=x.relayOff, args=(1,)) 

t1.start() 
t2.start() 
t3.start() 
t4.start() 

x.closeIfkit() 
+0

Я получил его на работу, изменяя t1, -T4, как указано выше, я не если это правильно или нет? Еще раз спасибо тем, кто ответил. –

ответ

2

Вам необходимо пройти вызываемый в target=, например, так:

t1 = threading.Thread(target=lambda: x.relayOff(1)) 

в данный момент, то, что ты звонишь x.relay* на основном потоке и передает ее возвращаемое значение (т.е. None, потому что в функциях python, которые не возвращаются явно, возвращает None) до target=.

0

Вы вызываете relayOn и relayOff два раза в каждом потоке и никогда в своих дочерних потоках, которые ничего не делают. target, что вы даете threading.Thread, является возвращаемым значением из relayOn или relayOff, который (поскольку эти функции ничего не возвращают) составляет None, поэтому нити ничего не запускают.

Один из способов исправить это было бы создать замыкание, которое делает то, что вы хотите:

t1 = threading.Thread(target=lambda: x.relayOn(0)) 

и т.д.