Tag: Finish write time relationship LSE Art process DNA
1. the difference between a process and a thread:
(1) a process can have multiple threads, and multiple threads in one process share all of the resources of the process, and multi-threaded switching is faster than multi-process switching, because there is no context switch, and concurrent recommendations in Python are multi-process
(2) A process is the smallest unit of resource allocation, and a thread is the smallest unit of program execution
(3) The process has its own independent address space, and the thread is the data in the shared process
2. Parallel and Concurrency: parallel refers to a second, concurrency refers to a time period
3. Pip List view each API version number
4. Daemon Thread: For example, the main thread A in the creation of child thread B, and in the main thread a called B.setdeamon (), meaning that the B is set as the daemon thread, if the main thread a execution is finished, not the pipe thread B is complete, and the main thread a exit. This is the meaning of the Setdaemon method, which is essentially the opposite of join. In addition, there is a special note that you must call this method before the start () method call, if it is not set to a daemon, it may be hung by wireless
5. Methods for thread creation:
(1) Threading. Thread Creation
(2) create a thread by inheriting the thread class: Class MyThread (Threading. Thread)
6. Thread-owned methods:
(1) isAlive () returns whether the thread is running. Run refers to the start, before the end.
(2) GetName () Get thread name
(3) SetName () set the thread name
(4) Isdeamon () To determine if a thread ended with the main threads
(5) Setdeamon () set whether to be a daemon thread
(6) Start () Start Thread
(7) Join () wait until all the child threads have finished executing to proceed
(8) Run () methods used to represent thread activity, often requiring overriding
(9) Pool.map ()
7. Two relationships of concurrent threads: synchronous and Mutex
(1) locks enable mutual exclusion between threads
(2) producers and consumers are examples of thread synchronization
8. line Cheng: Threading. Semaphore ()
#练习: Daemon import multiprocessingimport time, Loggingimport sysdef daemon (): P=multiprocessing.current_process () print'Starting:', P.name, P.pid Sys.stdout.flush () # writes buffer data to Terminal # Time.sleep (2) Print'Exiting:', P.name, P.pid Sys.stdout.flush () def non_daemon (): P=multiprocessing.current_process () print'non_starting:', P.name, P.pid sys.stdout.flush () print'non_exiting:', P.name, P.pid Sys.stdout.flush ()if__name__ = ='__main__': # Set the log output to console Multiprocessing.log_to_stderr () Logger=Multiprocessing.get_logger () # Sets the output log level logger.setlevel (logging. DEBUG) d= multiprocessing. Process (name='Daemon', target=daemon) D.daemon=True N= multiprocessing. Process (name='Non-daemon', target=Non_daemon) N.daemon=False D.start () time.sleep (1) N.start () # D.join (1) # n.join () print'd.is_alive ()', d.is_alive () print"n.is_alive ()", n.is_alive () print"main Process end!"#练习: Thread pool import time fromMultiprocessing.dummy Import Pool asThreadpool#threadpool represents an alias to the thread pool Threadpooldef run (FN): Time.sleep (2) print FNif__name__ = ="__main__": TESTFL= [1,2,3,4,5] #创建10个容量的线程池并发执行 Pool= ThreadPool (Ten) Pool.map (RUN,TESTFL) pool.close () Pool.join () #练习: Locks enable mutual exclusion between threads import Threadingimport timedata=0Lock=Threading. Lock () #创建一个锁对象def func ():GlobalData Print"%s Acquire lock...\n"%Threading.currentthread (). GetName ()if Lock. Acquire:#if1: Change to this time-consuming presidentPrint"%s Get lock...\n"%Threading.currentthread (). GetName () forIinchRange100000): Data+=1#mustLock#time. Sleep (2) #其它操作 Print"%s Release lock...\n"%Threading.currentthread (). GetName () #调用release () will release the lock #Lock. Release () StartTime=time.time () T1= Threading. Thread (target =func) T2= Threading. Thread (target =func) T3= Threading. Thread (target =func) T1.start () T2.start () T3.start () T1.join () T2.join () t3.join () print Dataendtime=time.time () print"used time is", EndTime-starttime# Exercise: Thread synchronization fromQueue Import Queue #队列类import Random import threading import time #生成者线程classProducer (Threading. Thread): Def __init__ (self, T_name, queue): #调用父线程的构造方法. Threading. Thread.__init__ (self, name=t_name) Self.data=Queue def run (self): forIinchRange5): Print"%s:%s is producing%d to the queue!\n"%(Time.ctime (), Self.getname (), i) self.data.put (i) #向队列中添加数据 #产生一个0-A random number between 2 for Sleep Time.sleep (Random.randrange (Ten) /5) Print"%s:%s finished!"%(Time.ctime (), Self.getname ()) #消费者线程classConsumer (Threading. Thread): Def __init__ (self, T_name, queue): Threading. Thread.__init__ (self, name=t_name) Self.data=Queue def run (self): forIinchRange5): Val= Self.data.Get() #从队列中取出数据 print"%s:%s is consuming.%d of the queue is consumed!\n"%(Time.ctime (), Self.getname (), Val) time.sleep (Random.randrange (Ten)) Print"%s:%s finished!"%(Time.ctime (), Self.getname ()) #Main thread Def Main (): Queue=Queue () #创建一个队列对象 (feature FIFO) producer= Producer ('Pro.', queue) #生产者对象 consumer= Consumer ('Con.', queue) #消费者对象 Producer.start () Consumer.start () Producer.join () consumer.join () print 'All Threads terminate!' if__name__ = ='__main__': Main () #练习: Thread lock fromThreading Import Thread, Lockimport threadingdef run (Lock, num):Lock. Acquire () # Gets the lock # gets the thread name of the current thread ThreadName=Threading.current_thread (). GetName () Print"%s, Hello Num:%s"%(ThreadName, num)Lock. Release () # Unlock lockif__name__ = ='__main__': Lock=Lock () # Create a shared lock instance forNuminchRange -): Thread (name='thread-%s'%STR (num), target = run, args = (Lock, num)). Start () #练习: multiple thread lock fromThreading Import Thread,lockimport threadingimport timedef Worker (s,i): S.acquire () print (threading.current_thr EAD (). Name+"Acquire") time.sleep (i) Print (Threading.current_thread (). Name+"Release") s.release ()if__name__=="__main__": S=threading. Semaphore (3) forIinchRange5): T=thread (target=worker,args= (s,i*2) ) T.start () #t. Join #这里加了join就会逐个执行了
"Python" Multithreading-2