python study notes (21) - Processes, Threads

1 , the process VS thread

process

  For the operating system, a task is a process.

  Implementation process instance of a program is a process, each process provide all the resources needed to execute the program.

  A process contains a main thread, zero or more child threads.

Thread

        A thread is the smallest unit of execution.

        Thread does not allocate their resources, all threads share resources processes simultaneously and threads.

Kind of thread

        The main thread

        Child thread

        Daemon thread

2 , multi-threaded

Python is multi-threading can not utilize multiple CPU, it can only run on a CPU.

Python threading module for use multithreading

Import Threading # thread module 
Import Time 

DEF RUN (URL): 
    the time.sleep ( 2 )
     Print (URL)
     Print ( ' running ... ' )
 DEF EAT ():
     Print ( ' eat ' ) 

START_TIME = the time.time () # stamp program begins to run 

threads = [] 

for I in Range (10 ):
     # instantiating a thread, run the function name 
    T of the threading.Thread = (target = rUN, args = ( ' HTTP: // WWW. baidu.com' ,)) # Parameter must add a comma 
    t.start () # start this thread 
    threads.append (t) # all child processes added to the list of threads 

# for threads in the Thread: 
#      Thread.join () # Use join the main thread will wait for the end of sub-thread execution then execute down 

# use join the above manner or way while loop 
# main thread waits for the child thread execution is complete and then perform the following procedures 
while threading.active_count () = 1:! # when the number of threads 1, until the end of the cycle 
    Pass 

Print (threading.active_count ()) # current number of threads 

END_TIME = the time.time () # timestamp when the program ends 
Print ( ' runtime ' , END_TIME-START_TIME) #This time when the main thread is finished executing code, does not contain a sub-thread execution time

 

Guess you like

Origin www.cnblogs.com/yanyan-/p/10966079.html