Python study day 44 (threads, join and setDaemon)

  Generally speaking yesterday, the concept of the process, by cpu switch between processes, the computer at the same time you realize the Internet, listening to music at the same time demand, then today to talk about the thread, the thread is in fact the essence of the process of miniaturization.

  First thread leads to what is proposed in order to meet what needs: We commonly used in computer txt notepad us in the course of daily use, you enter some text, notepad this program at the same time help you show in the display, while completing the entry saved disk function, which part do three things in the realization of:

  1. accepts input information from the keyboard;

  2. The content information on a display screen;

  3. The entry information saved on the hard disk.

  This time there is a demand, how to make it three steps at the same time, I wrote before seemingly is a single path mode (except socketserver module part), is the first complete write, then it reads, and finally save, so back to the actual the process of life is that you enter a bunch of information constantly, but you yourself can not see anything, and all your input finished, the computer will display the contents of your input, this time you did not modify the law as it has been to take the opportunity to save disk in, and this is obviously our real life situation is not the same.

  If the method used to resolve the process: three tasks three processes, cpu so far carried out in three tasks constantly switching, seemingly able to solve the problem, but there are two very obvious flaws:

  1. The process is exclusive section of memory that is input, save and reality to be run in three different memory areas;

  2. Based on 1 problem is caused by a defect in the process to be performed between the data communication, which is a very memory-consuming process, the same information constantly back and forth in the copy cpu, but also the process of switching, very worthwhile

  

Based on the above this demand, we introduced threads:

  Thread: a miniature process of internal procedures, share the entire process all memory resources, and brought two advantages:

  1. The concept of internal memory information does not exist in the information communication, shared processes

  2. Because the shared memory, so switching is more convenient, do not want to process so much trouble

Coupled with the concept of the process last night, we can get the following conclusions:

  Process: The minimum resource unit program

  Thread: The minimum program execution unit

 

  It appears to reduce the consumption of thread context switching, improve the concurrency of the system, and a breakthrough in the process of doing the same thing only drawback, Shidao concurrent in-process possible.

  Assume that a text program, you need to accept keyboard input, the content displayed on the screen, you also need to save the information to your hard drive. If only one process, will inevitably result in the same time you can only do the same thing embarrassing (When you save, you can not pass keyboard typing). If there are multiple processes, each responsible for a task, process A task is responsible for receiving keyboard input, process B is responsible for the content displayed on the screen task, process C is responsible for the task to save the contents of the hard disk. Here the process of collaboration between A, B, C involved in the process of communication problems, but there are things ------- text needs to have a common, non-stop switching loss in performance. If a mechanism can make the task A, B, C shared resources, such as context switching required to save and restore the contents of less, and at the same time can reduce the communication performance caused by wear and tear, so much the better. Yes, this mechanism is the thread.

  Thread, also known as lightweight processes, it is a basic CPU execution unit is the smallest unit of program execution process, by the thread ID, program counter, register set and stack together to form. The introduction of the thread reduces the overhead of concurrent execution of the program to improve the concurrent performance of the operating system. Thread does not have its own system resources.

 

  A program has at least one process, a process has at least one thread. (Thread can be understood as a process container) process has a separate memory unit in the implementation process, and multiple threads of shared memory, thereby greatly enhancing the efficiency of the program . Threads in the implementation process and the process is different. Each entry has a separate thread running, sequences and procedures performed in the order outlet. But the thread is not able to execute independently, it must exist according to the application, providing multiple execution threads controlled by the application. Process is a program with a certain separate functions run on one set of data on the activities of the process is a stand-alone system unit resource allocation and scheduling. A thread is a physical process, is the basic unit of CPU scheduling and dispatch, it is smaller than the process of the basic unit can operate independently. basically thread does not own its own system resources, has only a little in the operation of essential resources (such as a program counter, a set of registers and stack) but it may belong to the same process the entire resources of other threads share the process owned by
  a thread can be created and destroyed another thread; can execute concurrently across multiple threads in the same process.

 

Well, said so much, how to achieve multi-threading it (FML, before all single-threaded)

Today's focus (threading module)  

  threading module built on top of the thread module. lower thread module, the original way to handle and control thread, the thread for threading module by the second package provides a more convenient api treated threads.

  After listening to two days content, wood line of code was also strange palpitation, and now, I do not flustered

  Let me talk about the old model

import time

def listen(num):
    print('listen is coming at %s'%time.ctime())
    time.sleep(3)
    print('listen is ending at %s'%time.ctime())

def game(num):
    print('game is coming at %s'%time.ctime())
    time.sleep(5)
    print('game is ending at %s'%time.ctime())

if __name__ == '__main__':
    listen(1)
    game(1)
    print('ending time is %s'%time.ctime())

  At this time, the output (the program running from front to back order):  

  listen is coming at Mon Apr 6 23:59:52 2020
  listen is ending at Mon Apr 6 23:59:55 2020
  game is coming at Mon Apr 6 23:59:55 2020
  game is ending at Tue Apr 7 00:00:00 2020
  ending time is Tue Apr  7 00:01:47 2020

 

At this point we threading module and used as Thread class is instantiated:

  

import time
import threading

def listen(num):
    print('listen is coming at %s'%time.ctime())
    time.sleep(3)
    print('listen is ending at %s'%time.ctime())

def game(num):
    print('game is coming at %s'%time.ctime())
    time.sleep(5)
    print('game is ending at %s'%time.ctime())

if __name__ == '__main__':
    t1 = threading.Thread(target = listen , args = (1,))
    t1.start()
    t2 = threading.Thread(target = game , args = (2,))
    t2.start()
    print('ending time is %s'%time.ctime())

  At this point you will find that operating results, print ending on the main thread and the game, listen start of a run  

  listen is coming at Tue Apr 7 00:04:32 2020
  game is coming at Tue Apr 7 00:04:32 2020
  ending time is Tue Apr 7 00:04:32 2020
  listen is ending at Tue Apr 7 00:04:35 2020
  game is ending at Tue Apr 7 00:04:37 2020

At this point of the program, the addition of two branches with the main thread starts running simultaneously on the main thread

 

  So join and what does it mean?

  Seen on the results can understand

import time
import threading

def listen(num):
    print('listen is coming at %s'%time.ctime())
    time.sleep(3)
    print('listen is ending at %s'%time.ctime())

def game(num):
    print('game is coming at %s'%time.ctime())
    time.sleep(5)
    print('game is ending at %s'%time.ctime())

if __name__ == '__main__':
    t1 = threading.Thread(target = listen , args = (1,))
    t1.start()
    t1.join()
    t2 = threading.Thread(target = game , args = (2,))
    t2.start()
    print('ending time is %s'%time.ctime())

The following sequence, this time ending wait until the end of the run was a listen and start running game

So mean you know, he is then tied back to the main thread on

If the above procedure t2.start () also add back t2.join (), and is equivalent to the above it is a first look

 

The following is setDaemon (first glance, set A Dream)

import time
import threading

def listen(num):
    print('listen is coming at %s'%time.ctime())
    time.sleep(3)
    print('listen is ending at %s'%time.ctime())

def game(num):
    print('game is coming at %s'%time.ctime())
    time.sleep(5)
    print('game is ending at %s'%time.ctime())

if __name__ == '__main__':
    t1 = threading.Thread(target = listen , args = (1,))
    t1.setDaemon(True)
    t1.start()
    t2 = threading.Thread(target = game , args = (2,))
    t2.setDaemon(True)
    t2.start()
    print('ending time is %s'%time.ctime())

At this time, the output of the first I was shocked to see is the old saying this is a daemon thread, a quick guard, please optimistic:

  listen is coming at Tue Apr 7 00:13:23 2020
  game is coming at Tue Apr 7 00:13:23 2020
  ending time is Tue Apr 7 00:13:23 2020

After the main thread running, the other thread is not running, is so powerful. So called Guardian, this part seems to have more tonight too late listening to all, and tomorrow continue to add up.

  

join (): Before the child thread finishes running, the parent of the child thread thread will be blocked.

setDaemon(True):

         The thread is declared as a daemon thread must be set before the method is called start (), if you do not set a daemon thread hangs the program will be unlimited. This method is basic and join the opposite. When we are running, perform a main thread, if the main thread and create a child thread, the main thread and the child thread on the two forces were divided, were running, when the main thread finishes want to quit, will test the child thread is complete. If the child thread is not completed, the main thread will wait for the child threads to complete before exit. But sometimes we need is just the main thread finishes, regardless of whether the child thread to complete, and should be the main thread exits together, then you can use it setDaemon method

  Some common methods threading module

# Run (): thread run method is performed automatically after the thread object cpu scheduling 
# Start (): start thread activity. 
# IsAlive (): Returns the thread is active. 
# GetName (): Returns the thread name. 
# SetName (): Set the thread name. 

threading module provides a number of methods: 
# threading.currentThread (): Returns the current thread variable. 
# Threading.enumerate (): Returns a list of running threads. Refers to the thread starts running, before the end, does not include a thread before starting and after termination. 
# Threading.activeCount (): Returns the number of running threads, and len (threading.enumerate ()) have the same result.

Today is the content of these, and know instantly felt a thread after the previous low burst

Just glance at the dangers of staying up late, no, I have a lot of work to do, not lose any sleep, bye tomorrow.

 

Guess you like

Origin www.cnblogs.com/xiaoyaotx/p/12650722.html