How to use multiple threads

前端 未结 5 1696
臣服心动
臣服心动 2021-02-05 11:16

I have this code:

import thread

def print_out(m1, m2):
    print m1
    print m2
    print \"\\n\"

for num in range(0, 10):
    thread.start_new_thread(print_o         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 12:14

    First of all, you should use the higher level threading module and specifically the Thread class. The thread module is not what you need.

    As you extend this code, you most likely will also want to wait for the threads to finish. Following is a demonstration of how to use the join method to achieve that:

    import threading
    
    class print_out(threading.Thread):
    
        def __init__ (self, m1, m2):
            threading.Thread.__init__(self)
            self.m1 = m1
            self.m2 = m2
    
        def run(self):
            print self.m1
            print self.m2
            print "\n"
    
    threads = []
    for num in range(0, 10):
        thread = print_out('a', 'b')
        thread.start()
        threads.append(thread)
    
    for thread in threads:
        thread.join()
    

提交回复
热议问题