繁体   English   中英

使用Python的线程模块在类中对多个函数进行多线程

[英]Multithreading Multiple Functions Within A Class With Python's Threading Module

我已经成功地将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()

我能够弄清楚如何做到这一点。 在阅读了有关线程模块的更多信息之后,我能够对一个需要的线程进行编码,而不必对每个函数进行线程化。 这是我实际程序中的代码,而不是上面的代码;

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    

这是我创建和执行线程的地方。

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()

我仍在努力使线程无限运行,除非退出,所以现在我使用while循环和time.sleep()函数来运行脚本并仍然能够处理输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM