One, multi-threaded execution using threading module
- It can be seen that the use of multi-threaded concurrency is much less time consuming
- Creating a good thread requires invoking a
start() method to start
#Coding=utf-8ImportThreadingImport TimedefTest ():Print("----TEST by sqyy----") Time.sleep (1)if __name__=="__main__": forIinchRange (5): T= Threading. Thread (target=test) T.start ()#start a thread, that is, let the thread start executing
The above code runs the result
----Test by Sqyy--------test by Sqyy--------test by Sqyy--------test by Sqyy--------test by SQYY----
Second, use the thread subclass to complete the creation of multithreading
If more than one thread executes the same function, there is no effect between the individual
The main thread waits for all child processes to end before ending
#Coding=utf-8ImportThreadingImport TimeclassMyThread (Threading. Thread):defrun (self) forIinchRange (3): Time.sleep (1) msg="I ' m"+ Self.name +'@'+ STR (i)#The Name property holds the names of the current thread. Print(msg)if __name__=='__main__': T=MyThread () T.start ( )
The above code runs the result:
I'm Thread-1 @0i'm Thread-1 @1i'm Thread-1 @2
Third, the execution order of the thread
- Each thread must have a name, although the above example does not specify the name of the thread object, but Python automatically assigns a name to the thread.
- When the thread's run () method ends, the thread finishes.
- The thread scheduler cannot be controlled, but there are other ways to influence how threads are dispatched.
#Coding=utf-8ImportThreadingImport TimeclassMyThread (Threading. Thread):defRun (self): forIinchRange (3): Time.sleep (1) msg="I ' m"+self.name+' @ '+Str (i)Print(msg)defTest (): forIinchRange (5): T=MyThread () T.start ( )if __name__=='__main__': Test ()
The above code runs the result:
I'm Thread-1 @ 0I'm Thread-2 @ 0I'm Thread-5 @ 0I'm Thread-3 @ 0I'm Thread-4 @ 0I'm Thread-3 @ 1I'm Thread-4 @ 1I'm Thread-5 @ 1I'm Thread-1 @ 1I'm Thread-2 @ 1I'm Thread-4 @ 2I'm Thread-5 @ 2I'm Thread-2 @ 2I'm Thread-1 @ 2I'm Thread-3 @ 2
Four, multi-threaded global variable sharing
fromThreadingImportThreadImport Time#sharing global variables between threadsG_num = 100defWork1 ():GlobalG_num forIinchRange (3): G_num+ = 1Print("----in Work1, G_num is%d---"%g_num)defWork2 ():GlobalG_numPrint("----in Work2, G_num is%d---"%g_num)Print("---Thread was created before G_num is%d---"%g_num) T1= Thread (target=work1) T1.start ()#delay for a while to ensure that things in the T1 thread are doneTime.sleep (1) T2= Thread (target=work2) T2.start ()
The above code runs the result:
is-------on is 103-------on is 103---
"Code Learning" PYTHON thread