How can I use threading in Python?

前端 未结 19 2715
迷失自我
迷失自我 2020-11-21 04:54

I am trying to understand threading in Python. I\'ve looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I\'m having trou

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:31

    Just a note: A queue is not required for threading.

    This is the simplest example I could imagine that shows 10 processes running concurrently.

    import threading
    from random import randint
    from time import sleep
    
    
    def print_number(number):
    
        # Sleeps a random 1 to 10 seconds
        rand_int_var = randint(1, 10)
        sleep(rand_int_var)
        print "Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"
    
    thread_list = []
    
    for i in range(1, 10):
    
        # Instantiates the thread
        # (i) does not make a sequence, so (i,)
        t = threading.Thread(target=print_number, args=(i,))
        # Sticks the thread in a list so that it remains accessible
        thread_list.append(t)
    
    # Starts threads
    for thread in thread_list:
        thread.start()
    
    # This blocks the calling thread until the thread whose join() method is called is terminated.
    # From http://docs.python.org/2/library/threading.html#thread-objects
    for thread in thread_list:
        thread.join()
    
    # Demonstrates that the main process waited for threads to complete
    print "Done"
    

提交回复
热议问题