The content of this section
- What is a thread
- The difference between a thread and a process
- Two ways to turn on threads
- Other properties or methods of the thread object
- Daemon Threads
- Gil Global Interpreter Lock
- Deadlocks and recursive locks
- Semaphore Event Timer
- Thread queue
What is a thread
Line threads is more lightweight for processes, when a process starts and starts a main thread, multithreading means creating multiple threads under one process and sharing the address space with those threads. So the process is just for pooling the resources together (the process is just a resource unit, or a resource collection), and the thread is the executing unit on the CPU.
The difference between the second process and the progress
1 Threads share the address space of the process that created it; Processes has their own address space.
2 Threads has direct access to the data segment of its process; Processes has their own copy of the data segment of the parent process.
3 Threads can directly communicate with other Threads of its process; Processes must use interprocess communication to communicate with sibling processes.
4 New threads is easily created; New processes require duplication of the parent process.
5 Threads can exercise considerable control over Threads of the same process; Processes can only exercise control over the child processes.
6 changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the pro Cess; Changes to the parent process does isn't affect child processes.
To summarize the above differences, there are two key points, which is why we need to use multithreading in a particular scenario:
Multiple threads within the same process share address resources within the process
The cost of creating a thread is much less than the cost of creating the process (creating a process, creating a workshop, involving the application space, and building at least one pipeline within that space, but creating a thread that creates a pipeline in a single workshop without requesting space, so the creation cost is small)
Three ways to turn threads on by opening threads
Way One fromThreadingImportThreadImport TimedefSayhi (name): Time.sleep (2) Print('%s Say hello'%name)if __name__=='__main__': T=thread (target=sayhi,args= ('Harry',)) T.start ()Print('Main Thread') mode two fromThreadingImportThreadImport TimeclassSayhi (Thread):def __init__(Self,name): Super ().__init__() Self.name=namedefRun (self): Time.sleep (2) Print('%s Say hello'%self.name)if __name__=='__main__': T= Sayhi ('Harry') T.start ()Implementation of socket communication based on multi-process multithreading
1 ImportSocket2 fromMultiprocessingImportProcess3 fromThreadingImportThread4 5 defcreate_socket ():6Server =Socket.socket (socket.af_inet, socket. SOCK_STREAM)7Server.bind (('127.0.0.1', 8080))8Server.listen (5)9 returnServerTen One defTalk (conn): A - whileTrue: - Try: thedata = CONN.RECV (1024) - ifData isNone: Break - Conn.send (Data.upper ()) - exceptConnectionerror: + Break - conn.close () + A defCommunication (server): at - whileTrue: -Conn,add =server.accept () -t = Thread (Target=talk, args=(conn,)) - T.start () - in if __name__=='__main__': -Server =Create_socket () toP1 = Process (target=communication, args=(server,)) +P2 = Process (target=communication, args=(server,)) - P1.start () theP2.start ()View CodeWrite a simple text processing tool with three tasks, one to receive user input, one to format user input, and one to file formatted results
1 fromThreadingImportThread2msg_l = []3format_l = []4 5 defuser_input ():6 whileTrue:7Text = input ('Please enter the content:')8 ifText isNone:Continue9 msg_l.append (text)Ten One A defformat_text (): - whileTrue: - ifmsg_l: theReg =Msg_l.pop () - Format_l.append (Reg.upper ()) - - defSave (): + whileTrue: - ifformat_l: +With open ('Db1.txt','a', encoding='Utf-8') as F: Ares =Format_l.pop () atF.write ('%s\n'%Res) - F.flush () - - if __name__=='__main__': - -T1 = Thread (target=user_input) inT2 = Thread (target=format_text) -T3 = Thread (target=Save) to + T1.start () - T2.start () theT3.start ()View Code
Other properties or methods of the four thread object
methods for thread instance objects # isAlive (): Returns whether the thread is active. # getName (): Returns the thread name. # setName (): Sets the thread name.
Some of the methods provided by the threading module are: # threading.currentthread (): Returns the current thread variable. # threading.enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends. # threading.activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).
Five Daemon threads
Whether it is a process or a thread, follow: Guardian xxx will wait for the main xxx to be destroyed after the completion of the operation
It should be emphasized that the operation is not terminated
1, for the main process, run complete refers to the main process code is finished running
2, to the main thread, said, run complete refers to the main thread is in the process of all the non-daemon threads run complete, the main thread is run complete
Detailed Explanation:
1, the main process in its code after the end of the run is finished (the daemon is recycled at this time), and then the main process will always wait until the non-Guardian child process is completed after the completion of the child process resources (otherwise, will produce a zombie process), will end,
2. The main thread runs after the other non-daemon threads have finished running (the daemon thread is recycled at this time). Because the end of the main thread means the end of the process, the resources of the process as a whole are recycled, and the process must ensure that the non-daemon threads are finished before they end.
Consider what might be the results of the following code execution? Why?
fromThreadingImportThreadImport Timedeffoo ():Print(123) Time.sleep (1) Print("end123")defBar ():Print(456) Time.sleep (3) Print("end456")if __name__=='__main__': T1=thread (target=foo) T2=thread (target=bar) T1.daemon=True T1.start () T2.start ()Print("main-------"The above code will first output123,456,main, the end123,end456 is then output. Because the T1 daemon is the main process, let the main process finish executing print ("main-------"Thread 2 is already running, so the main process does not end, and the child process will not be recycled until the sub-thread has finished running the resource process.
Python concurrent programming Multi-Threading