Python threads
Threading is used to provide thread-related operations, which are the smallest unit of work in an Application.
#!/usr/bin/env Python#-*-coding:utf-8-*-import threadingimport time def show (arg): time.sleep (1) Print ' Thread ' +str (arg) for i in range: t = threading. Thread (target=show, args= (i,)) t.start () print ' main thread stop '
The code above creates 10 "foreground" threads, then the controller is handed over to the CPU,CPU according to the specified algorithm for scheduling, shard execution Instructions.
More Ways:
- Start thread is ready to wait for CPU scheduling
- SetName setting a name for a thread
- GetName Get thread Name
- Setdaemon set to background thread or foreground thread (default)
If it is a background thread, during the main thread execution, the background thread is also in progress, and after the main thread finishes executing, the background thread stops regardless of success or Not.
If it is the foreground thread, during the main thread execution, the foreground thread is also in progress, and after the main thread finishes executing, wait for the foreground thread to finish, the program stops
- The join executes each thread one by one and continues execution after execution, making multithreading meaningless
- The Run method that executes the thread object automatically after the run thread is dispatched by the CPU
ImportThreadingImport timeclassMyThread (threading. Thread):def __init__(self,num): Threading. Thread.__init__(self) Self.num=NumdefRun (self):#define the functions to be run by each thread Print("running on number:%s"%Self.num) Time.sleep (3) if __name__=='__main__': T1= MyThread (1) T2= MyThread (2) T1.start () t2.start ()
Custom Threading Classes
Thread Lock (lock, Rlock)
Because there is a random dispatch between threads, and each thread may execute only n, dirty data may appear when multiple threads modify the same piece of data at the same time, so a thread lock is present-allowing one of the threads to perform the operation at the same time.
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImportTimegl_num=0defShow (arg):Globalgl_num Time.sleep (1) Gl_num+=1PrintGl_num forIinchRange (10): T= Threading. Thread (target=show, args=(i,)) T.start ()Print 'Main thread Stop'
Lock not used
#!/usr/bin/env python#coding:utf-8 Import threadingimport time gl_num = 0 lock = threading. Rlock () def Func (): lock.acquire () global gl_num gl_num +=1 time.sleep (1) Print Gl_ Num lock.release () for i in range: t = threading. Thread (target=func) T.start ()
Signal Volume (Semaphore)
mutexes allow only one thread to change data at the same time, while Semaphore allows a certain number of threads to change data, such as a toilet with 3 pits, which allows up to 3 people to go to the toilet, while the latter can only wait for someone to come Out.
Import Threading,time def run (n): semaphore.acquire () time.sleep (1) print ("run the Thread:%s"%n) Semaphore.release () If __name__ = = ' __main__ ': num= 0 semaphore = threading. Boundedsemaphore (5) #最多允许5个线程同时运行 for i in range: t = threading. Thread (target=run,args= (i,)) t.start ()
Events (event)
The events of the Python thread are used by the main thread to control the execution of other threads, and the event provides three methods set, wait, clear.
Event handling Mechanism: A global definition of a "flag", if the "flag" value is False, then when the program executes the Event.wait method is blocked, if the "flag" value is true, then the Event.wait method will no longer block.
- Clear: set "Flag" to False
- Set: sets "Flag" to True
#!/usr/bin/env python#-*-coding:utf-8-*-import Threading def do (event): print ' start ' event.wait () print ' execute ' event_obj = threading. Event () for i in range: t = threading. Thread (target=do, args= (event_obj,)) t.start () event_obj.clear () inp = raw_input (' input: ') if InP = = ' true ': Event_obj.set ()
Conditions (Condition)
Causes the thread to wait, releasing n threads only if a condition is met
Import Threading def Run (n): con.acquire () con.wait () print ("run the Thread:%s"%n) con.release () if __name__ = = ' __main__ ': con = threading. Condition () for i in range: t = threading. Thread (target=run, args= (i,)) t.start () while True: INP = input (' >>> ') if inp = = ' Q ': break con.acquire () con.notify (int (inp)) con.release ()
defCondition_func (): ret=False INP= Input ('>>>') ifINP = ='1': Ret=Truereturnretdefrun (n): con.acquire () con.wait_for (condition_func)Print("Run the thread:%s"%N) con.release ()if __name__=='__main__': Con=Threading. Condition () forIinchRange (10): T= Threading. Thread (target=run, args=(i,)) T.start ()
Timer
timer, specifying n seconds after an action is performed
From threading Import timer def hello (): print (' hello, world ') t = Timer (1, hello) t.start () # after 1 seconds, "hello, world" would be printed
Python process
From multiprocessing import Processimport threadingimport time def foo (i): print ' say hi ', i- i in range (10 ): p = Process (target=foo,args= (i,)) p.start ()
Note: because the data between processes needs to be held separately, the creation process requires very large overhead.
Process data sharing
The process holds one piece of data, and the data is not shared by default
#!/usr/bin/env python#Coding:utf-8 fromMultiprocessingImportProcess fromMultiprocessingImportManagerImporttime Li= [] deffoo (i): li.append (i)Print 'say hi', Li forIinchRange (10): P= Process (target=foo,args=(i,)) P.start ()Print 'ending', Li
#方法一, arrayfrom multiprocessing Import process,arraytemp = Array (' i ', [11,22,33,44]) def Foo (i): temp[i] = 100+i For item in temp: print i, '-----> ', item for i in range (2): p = Process (target=foo,args= (i,)) p.start () #方法 Ii: manage.dict () shared data from multiprocessing import process,manager manage = Manager () dic = manage.dict () def Foo (i): DiC [i] = 100+i print dic.values () for i in range (2): p = Process (target=foo,args= (i,)) p.start () p.join ()
'C': ctypes.c_char,'u': ctypes.c_wchar,'b': ctypes.c_byte,'B': ctypes.c_ubyte,'h': ctypes.c_short,'H': ctypes.c_ushort,'I': ctypes.c_int,'I': ctypes.c_uint,'L': ctypes.c_long,'L': ctypes.c_ulong,'F': ctypes.c_float,'D': ctypes.c_double
Type Correspondence Table
fromMultiprocessingImportProcess, QueuedefF (i,q):Print(i,q.get ())if __name__=='__main__': Q=Queue () q.put ("H1") Q.put ("H2") Q.put ("H3") forIinchRange (10): P= Process (target=f, args=(i,q,)) P.start ()
Code
When the process is created (when not in use), the shared data is taken to the child process, and is then assigned to the original value when the process finishes Executing.
#!/usr/bin/env python#-*-coding:utf-8-*- fromMultiprocessingImportProcess, Array, RlockdefFoo (lock,temp,i):"""add a No. 0 number to the"""lock.acquire () temp[0]= 100+I forIteminchtemp:PrintI'----->', item lock.release () lock=Rlock () Temp= Array ('I', [11, 22, 33, 44]) forIinchRange (20): P= Process (target=foo,args=(lock,temp,i,)) P.start ()
Process Lock Instance
Process Pool
A process sequence is maintained internally by the process pool, and when used, a process is fetched in the process pool, and the program waits until a process is available in the process pool sequence if there are no incoming processes available for Use.
There are two methods in a process pool:
- Apply
- Apply_async
#!/usr/bin/env python#-*-coding:utf-8-*-from multiprocessing Import process,poolimport time def Foo (i): time.sleep (2) return i+100 def Bar (arg): print arg pool = Pool (5) #print pool.apply (Foo, (1,)) # Print Pool.apply_async (func =foo, args= (1,)). get () for i in range: pool.apply_async (func=foo, args= (i,) , Callback=bar) print ' End ' pool.close () pool.join () #进程池中进程执行完毕后再关闭, If commented, then the program closes DIRECTLY.
Co-processThe operation of the thread and process is triggered by the program to trigger the system interface, The final performer is the system, and the operation of the coprocessor is the Programmer.
The significance of the existence of the process: for multi-threaded applications, the CPU by slicing the way to switch between threads of execution, thread switching takes time (save state, next continue). , only one thread is used, and a code block execution order is specified in one Thread.
Application Scenario: When there are a large number of operations in the program that do not require the CPU (IO), it is suitable for the association process;
Greenlet
#!/usr/bin/env python#-*-coding:utf-8-*-from greenlet import greenlet def test1 (): print Gr2.switch () Print gr2.switch () def test2 (): print gr1.switch () Print Gr1 = Greenlet (test1) GR2 = Greenlet (test2) gr1.switch ()
GeventImport gevent def foo (): print (' Running in foo ') gevent.sleep (0) print (' Explicit context Switch to Foo Again ') def bar (): print (' Explicit context to bar ') gevent.sleep (0) print (' implicit context switch back To bar ') gevent.joinall ([ gevent.spawn (foo), gevent.spawn (bar),])
Automatic switching of IO operation Encountered:
fromGeventImportmonkey; Monkey.patch_all ()ImportgeventImportUrllib2defF (url):Print('GET:%s'%Url) resp=urllib2.urlopen (url) Data=Resp.read ()Print('%d bytes received from%s.'%(len (data), url)) gevent.joinall ([gevent.spawn (f,'https://www.python.org/'), gevent.spawn (f,'https://www.yahoo.com/'), gevent.spawn (f,'https://github.com/'),])
View Code
threads, processes, and Co-routines