Python thread, Process knowledge collation

Source: Internet
Author: User

A. Python thread

Threading is used to provide thread-related operations, which are the smallest unit of work in an application.

1234567891011121314 #!/usr/bin/env python# -*- coding:utf-8 -*-importthreadingimporttime defshow(arg):    time.sleep(1)    print‘thread‘+str(arg) forinrange(10):    =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 Class
      Custom Threading Classes

Two. 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
Lock not used


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.

Three. Semaphore (Semaphore)

123456789101112131415 import threading,timedef 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个线程同时运行    forinrange(20):        t = threading.Thread(target=run,args=(i,))        t.start()

Four. 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

Five. Conditions (Condition)

Causes the thread to wait, releasing n threads only if a condition is met

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 ()
View Code

six. Timer

Seven. Python process

Eight. 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', there is no data sharing between Li processes by default
no data sharing between processes by default

'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
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
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.

Nine. 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
12345678910111213141516171819202122 #!/usr/bin/env python# -*- coding:utf-8 -*-frommultiprocessing import Process,Poolimporttime defFoo(i):    time.sleep(2)    returni+100  defBar(arg):    printarg pool =Pool(5)#print pool.apply(Foo,(1,))#print pool.apply_async(func =Foo, args=(1,)).get() forinrange(10):    pool.apply_async(func=Foo, args=(i,),callback=Bar) print ‘end‘pool.close()pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。

Python thread, Process knowledge collation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.