Defining threads
The simplest method: Use target to specify the target function to be executed by the thread and start with start ().
Grammar:
Class Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})
Group constant is None, reserved for future use. Target is the name of the function to execute. Name is the thread name and defaults to Thread-n, which is usually used by default. But the server-side program thread does not have the same function, it is recommended to name.
#!/usr/bin/env python3# coding=utf-8import threadingdef function (i): print ("function called by thread {0}". Format (i)) t Hreads = []for i in Range (5): T = Threading. Thread (Target=function, args= (i,)) Threads.append (t) T.start () T.join ()
Execution Result:
$./threading_define.py function called by thread 0function called by thread 1function called by thread 2function called B Y thread 3function called by thread 4
Determining the current thread
#!/usr/bin/env python3# coding=utf-8import threadingimport timedef first_function (): print (Threading.currentthread () getName () + str (' is starting \n ')) time.sleep (3) print (Threading.currentthread (). GetName () + str ( ' is exiting \n ')) def second_function (): print (Threading.currentthread () getName () + str (' is starting \n ')) time.sleep (2) print (Threading.currentthread (). GetName () + str ( ' is exiting \n ')) def third_function (): print (Threading.currentthread () getName () + str (' is starting \n ')) time.sleep (1) print ( Threading.currentthread (). GetName ()+ str ( ' is exiting \n ') if __name__ == "__ main__ ": t1 = threading. Thread (name= ' first_function ', target=first_function) t2 = threading. Thread (name= ' second_function ', target=second_function) t3 = threading. Thread (name= ' third_function ', target=third_function) t1.start () T2.start () t3.start ()
Execution Result:
$./threading_name.py First_function is starting second_function are starting third_function is Starting third_function are Exiting Second_function is Exiting first_function is Exiting
Use with the logging module:
#!/usr/bin/env python3# coding= Utf-8import loggingimport threadingimport timelogging.basicconfig ( level =logging. debug, format= ' [% (levelname) s] (% (threadname) -10s) % (message) s ', ) def worker (): logging.debug (' Starting ') time.sleep (2) logging.debug (' Exiting ') def my_service (): logging.debug (' starting ') time.sleep (3) logging.debug (' Exiting ') t = threading. Thread (name= ' My_service ', target=my_service) w = threading. Thread (name= ' worker ', target=worker) w2 = threading. Thread (Target=worker) # use default namew.start () W2.start () T.start ()
Execution Result:
$./threading_names_log.py[debug] (worker) Starting[debug] (Thread-1) Starting[debug] (My_service) Starting[debug] ( Worker) Exiting[debug] (Thread-1) Exiting[debug] (my_service) Exiting
Using Threads in subclasses
Our threads are all created in the form of structured programming. By integrating threading. The thread class can also create threads. The thread class first finishes some basic initialization and then calls its run (). The run () method invokes the target function passed to the constructor.
#!/usr/bin/env python3# coding=utf-8import loggingimport threadingimport timeexitflag = 0class myThread (Threading. Thread): def __init__ (Self, threadid, name, counter): threading. Thread.__init__ (self) self.threadID = threadID self.name = name self.counter = counter Def run (self): print ("starting " + Self.name) print_time (self.name, self.counter, 5) print ("exiting " + self.name) &nbSp;def print_time (Threadname, delay, counter): while counter: if exitFlag: thread.exit () time.sleep (delay) print ("%s: %s" % (Threadname, time.ctime ( Time.time ())) counter -= 1 # create new threadsthread1 = mythread (1, "Thread-1", 1) Thread2 = mythread (2, "Thread-2", 2) # start new Threadsthread1.start () Thread2.start () print ("Exiting main thread")
Execution Result:
$./threading_subclass.py starting thread-1starting thread-2exiting Main ThreadThread-1: Tue Sep 11:03:21 2015thread-2 : Tue Sep 11:03:22 2015thread-1: Tue Sep 11:03:22 2015thread-1: Tue Sep 11:03:23 2015thread-2: Tue Sep 15 11:03:2 4 2015thread-1: Tue Sep 11:03:24 2015thread-1: Tue Sep 11:03:25 2015Exiting thread-1thread-2: Tue Sep 15 11:03:26 20 15thread-2: Tue Sep 11:03:28 2015thread-2: Tue Sep 11:03:30 2015Exiting Thread-2
Python module Introduction-threading: Thread Management concurrency operations