2016-10-30 5 views
0

클래스 내의 단일 함수에 Pythons Threading 모듈을 사용하여 성공했지만 클래스 내의 여러 함수로 확장하려고합니다. 예를 들어, 일부 데이터를 구문 분석하는 프로그램이 있습니다. 메인 클래스가 있고 메인 클래스 내에 처리되는 데이터와 다른 일을하는 여러 함수가 있습니다. 각 함수는 특정 조건이 충족 될 때 호출됩니다. 여기에 내 프로그램과 유사한 기능으로 구성된 프로그램이 있습니다.Python의 스레딩 모듈을 사용하여 클래스 내에서 다중 함수 다중 스레딩

class MainClass(): 
    def __init__(self): 

     while True: 
      rawData=self.receiveData(file) #a made up function to receive data 
      stuffOne, stuffTwo, stuffThree, stuffFour, data=self.MainParseFunction(rawData) #returns four things and some data 

      if stuffOne=="a": 
       self.functionOne(data) 
       print("Output of Function One") 
      elif stuffTwo=="b": 
       self.functionTwo(data) 
       print("Output of Function Two") 
      elif stuffThree=="c": 
       self.functionThree(data) 
        print("Output of Function Three") 
      elif stuffFour=="d": 
       self.functionFour(data) 
        print("Output of Function Four") 

    def MainParseFunction(self, data): 
     '''Do some stuff to the data being passed to my function and return a bunch of variables to be use in the other functions '''   
    def functionOne(self, data): 
     '''Do some stuff to the data being passed to my function and return a bunch of variables to be printed ''' 
    def functionTwo(self, data): 
     '''Do some stuff to the data being passed to my function and return a bunch of variables to be printed ''' 
    def functionThree(self, data): 
     '''Do some stuff to the data being passed to my function and return a bunch of variables to be printed ''' 
    def functionFour(self, data): 
     '''Do some stuff to the data being passed to my function and return a bunch of variables to be printed ''' 

if __name__ == ('__main__'): 
    MainClass() 

실제 프로그램은 더 복잡하고 처리 속도를 높이기 위해 스레딩을 사용하려는 많은 데이터를 실제로 처리하지만. 하나의 함수를 호출 할 때 스레드를 호출하고 다른 하나는 호출 할 때 스레드를 처리하고 싶습니다. 대부분의 예제에서는 다중 함수가 아닌 단일 함수 만 대상으로했습니다. 나는 이것이 가능하다라고 생각한다 나는 단지 이것에 관해 가야하는지 모른다.

def threader(): 
     while True: 
      job=self.q.get() 
      self.MainParseFunction(job) 
      self.q.task_done() 

for _ in range(10): 
    t=threading.Thread(target=self.functionOne) 
    t.daemon=True 
    t.start() 

for job in range(1,500): 
    self.q.put(job) 

self.q.join() 
+0

각 기능을 하나의 스레드로 시작하는 것으로 충분하지 않습니까? 제 말은 ...'t1 = threading.Thread (target = self.functionOne); t2 = threading.Thread (target = self.functionTwo); t3 = threading.Thread (target = self.functionThree) ... '등등? – BorrajaX

답변

0

이 작업을 수행하는 방법을 파악할 수있었습니다. 스레딩 모듈에 대한 자세한 내용을 읽은 후에 각 함수를 스레드하지 않고도 필요한 스레드를 코딩 할 수있었습니다. 위의 코드가 아니라 실제 프로그램의 코드입니다.

class PacketSniffer(threading.Thread): 
def __init__(self, rawData, currentTime): 
    super(PacketSniffer,self).__init__() 
    self.rawData=rawData 
    self.currentTime=currentTime 

    destinationMAC, sourceMAC, etherType, data = self.Ethernet_Frame(self.rawData) 
    print("\t Ethernet Frame - {} - Destination: {}, Source: {} Protocol: {}".format(self.currentTime, destinationMAC, sourceMAC, etherType)) 

    if etherType.__eq__(8): 
     version, headerLength, TTL, protocol, source, destination, packetData=self.IPv4_Packet(data) 
     print("\t IPv4 Packet - {} - Version: {}, Header Length: {}, TTL: {}, Protocol: {}, Source: {} Destination: {}".format(self.currentTime, version, headerLength, TTL, protocol, source, destination)) 

     if protocol.__eq__(1): 
      ICMP_type, code , checksum, packetData=self.ICMP_Packet(data) 
      print("\t ICMP Packet - {} - ICMP Type: {}, Code: {}, TTL: {}, Checksum: {}".format(self.currentTime, ICMP_type, code, checksum)) 

     elif protocol.__eq__(6): 
      sourcePort, destinationPort, seqNumber, destNumber, urgFlag, ackFlag, pshFlag, rstFlag, synFlag, finFlag, tcpData=self.TCP_Packet(data) 
      print("\t TCP Packet - {} - Source Port: {}, Destination Port: {}, Sequence Number: {}, Acknowledgment: {}, URG Flag: {}, ACK Flag: {}, PSH Flag: {}, RST Flag: {}, SYN Flag: {}, FIN Flag: {}".format(self.currentTime, sourcePort,destinationPort, seqNumber, destNumber, urgFlag, ackFlag, pshFlag, rstFlag, synFlag, finFlag)) 

     elif protocol.__eq__(17): 
      sourcePort, destinationPort, datagramLength, udpData=self.UDP_Packet(data) 
      print("\t UDP Packet - {} - Source Port: {}, Destination Port: {}, Datagram Length: {}".format(currentTime,sourcePort, destinationPort, datagramLength)) 
     else: 
      pass  

여기 내 스레드를 만들고 실행하는 곳입니다. 나는 아직도 내가 지금 내 스크립트를 실행하고 여전히 출력을 처리 할 수 ​​있도록 while 루프와 time.sleep() 함수를 사용하고 위해 이렇게 종료하지 않는 한 내 스레드가 무한 실행 가지고 일하고

if __name__.__eq__('__main__'): 
try: 
    connection=socket(AF_PACKET, SOCK_RAW, ntohs(0x0003)) 
except error: 
    print('Connection could not be established. Program exiting!') 
    sys.exit() 
rawData, address = connection.recvfrom(65535) 
currentTime = time.asctime(time.localtime(time.time())) 
while True: 
    thread=threading.Thread(target=PacketSniffer, args=(rawData, currentTime)) 
    thread.daemon=True 
    time.sleep(1) 
    thread.start() 
thread.join()