簡體   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