pytnon-thread, process

1. What thread, what process

  1. Process

    It is the integration of resources. A program is a process for the operating system, such as opening a browser, opening a word, etc. are all opening a process.

  2. Thread

  Is a program which most small execution units . Help the process work, the threads are independent of each other

    Multi-threading is used to handle frequent writes and reads of IO-intensive tasks. The CPU is responsible for scheduling and consumes disk space.

  3. Threads are contained in a process, a process can have multiple threads

  4. There is a thread in a process by default

  5. Main thread and sub-thread, a program has a main thread by default, and the main thread starts the sub-thread

 

Import module

import threading

Traditional way (single thread)

def down_load():
    time.sleep(5)
    print('运行完成')
    
for i in range(3):
    down_load()

Multi-threaded

 

for I in Range (. 3 ): 
    T = of the threading.Thread (target = down_load )             # instantiate a thread 
    t.start ()                                        # runs

 

  Don't bring down_load (), otherwise it belongs to itself and the 

threads are independent of each other
= T1 the time.time ()
 for I in Range (. 3 ): 
    T = of the threading.Thread (target = down_load)             # instantiate a thread 
    t.start ()                                        # starts running 

Print ( ' runtime ' , the time.time () -t1)

  The above code has a total of 4 threads, 3 threads are started in the loop, and there is a main thread running, so the results are as follows

The main thread runs to end the printing run time, and then waits for the child thread to end

Operation time 0.0009999275207519531 
Operation completion 
Operation completion 
Operation completion

 

View the current number of threads and threads

Print (threading.active_count ())                  # View Threads 
Print (threading.current_thread ())                # View the current thread
Main thread waits for child thread to end (parallel)
def down_load (): 
    time.sleep ( 5 )
     print ( ' Run completed ' ) 


# multi-thread 
t1 = time.time ()
 for i in range (3 ): 
    t = threading.Thread (target = down_load) 
    t.start ( ) 
    # t.join () # this is not a parallel structure tree 
# t.join () # here waiting for the end of the last thread of time 

the while threading.activeCount () = 1:!                   # main thread waits for the child thread end 
    pass

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/cwl-bj/p/12683621.html