How to use multiple threads

前端 未结 5 1756
臣服心动
臣服心动 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 11:54

    Whenever you are creating thread you need to run main thread before that. Here you are not running any main tread.

    To solve the problem you can add a print statement of any other statement. Lets modify your code

    import thread
    import time
    
    def print_out(m1, m2):
        print m1
        print m2
        print "\n"
    
    for num in range(0, 10):
        thread.start_new_thread(print_out, ('a', 'b'))
        time.sleep(.1)
    

    Here time.sleep() is creating main tread for you and thread.start_new_thread creating 10 threads on the main tread. Note: You can add any statement in place of time.sleep()

提交回复
热议问题