Python multithreaded programming (iii) : important functions and methods of the threading.Thread class

  • 2020-05-05 11:25:39
  • OfStack

This article focuses on the main methods of Thread, the main class in the threading module, with the following example code:


''' 
Created on 2012-9-7 
 
@author:  walfred
@module: thread.ThreadTest3 
@description:
'''   
import threading 
 
class MyThread(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self) 
 
    def run(self): 
        print "I am %s" % (self.name) 
 
if __name__ == "__main__": 
    for i in range(0, 5): 
        my_thread = MyThread() 
        my_thread.start()

name

You can specify name for each thread. The default is in the form Thread-No, as printed in the example code above:


I am Thread-1
I am Thread-2
I am Thread-3
I am Thread-4
I am Thread-5

Of course you can specify name for each thread, this one via the setName method, code:


def __init__(self): 
    threading.Thread.__init__(self) 
    self.setName("new" + self.name)

join method

The join method prototype is used to block the current context until the thread runs:


def join(self, timeout=None): 
        timeout You can set a timeout
timeout You can set timeout nibble

setDaemon method

When we run the program, execute a main thread, if the main thread and create a child thread, the main thread and the child thread on the two separate, when the main thread finish want to exit, will check whether the child thread finish. If the child thread does not complete, the main thread waits for the child to complete before exiting. But sometimes what we need is to exit with the main thread as soon as the main thread is finished, regardless of whether the thread is finished. In this case, we can use the setDaemon method and set its parameter to True.

Of course, this is just a list of the methods we often use in programming. For more, see: Higher-level threading interface  


Related articles: