python syntax basis - Concurrent Programming - thread - the thread and the thread starts theory

####################### thread introduction ######################### #####

"""
Introduction Thread

Why is there a process?
Mainly to process multiple tasks, also a plurality of tasks are switched round-robin
Why is there a thread?
The process is not the smallest unit to perform a task, each process there are a thread, we called the main thread,
Early no thread, a process can only do one task, if there is more than one task, only more than the process, the process does not work too much,
The internal memory is shared process, it is necessary to thread, or even related to the inter-process communication, which compares a waste of resources

So there are threads solves two problems:
1 internal process communication
2, a process that can handle multiple tasks,

Overhead thread less than the process can be considered a lightweight process,
The process is the smallest unit of resource allocation, the thread is the smallest unit cpu scheduling,

Processes and threads difference:
1, memory between processes are independent, but the threads within a process it can be shared,
2, switching between processes is slower than switching between threads,
"""

 

Two ways ################## threads started ###############

"" " 
Use threads in python threading module multiprocess module completely mimics the threading module interfaces, both at the level of use, there are a lot of similarities, and thus will not be described in detail """ # The first way to start: from threading import Thread import team, the def func (n): # This is the child thread completed time.sleep (1) # Although it is printed 10 times, but just wait one second, it is between 10 concurrent threads, print(n) for i in range (10): # start 10 threads, t = Thread(target=func,args=(i,)) # 注册 t.start () # This is the start of a thread # The second method to start the thread: # class MyTread(Thread): # def __init__(self,arg): # super().__init__() # = Arg self.arg # def run(self): # time.sleep(1) # print(1,os.getpid()) # for i in range(10): # T = MyTread (10) # pass parameters # t.start() # # Print ( "main thread", os.getpid ()) # print main process and sub-process of process ID is the same

Other methods of the Thread class

# Threading in other ways
from threading import Thread
import time
def sayhi(name):
    time.sleep(2)
    print('%s say hello' %name)
if __name__ == '__main__': t=Thread(target=sayhi,args=('egon',)) t.start() t.join() print('主线程') print(t.is_alive()) ''' egon say hello 主线程 False ''' ############################################### import threading def func(n): print(n, threading.current_thread()) # <Thread(Thread-1, started 5428)> for i in range(10): threading.Thread(target=func, args=(1,)).start() print(threading.active_count()) # 查看活跃的线程数, print(threading.current_thread())

 

Guess you like

Origin www.cnblogs.com/andy0816/p/12375813.html