Python: Brief description of threads, processes, and co-routines

Source: Internet
Author: User
Tags thread stop

Python threads

Definition: 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

Thread Lock

The CPU then executes other threads because the threads are randomly dispatched, and each thread may execute only n execution. Therefore, the following problems may occur:

Import Threadingimport Timegl_num = 0def Show (ARG):    global Gl_num    time.sleep (1)    gl_num +=1    Print Gl_ Numfor i in range:    t = Threading. Thread (target=show, args= (i,))    T.start () print ' main thread stop '
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 ()

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 ()
Python Process
From multiprocessing import Processimport threadingimport time  def foo (i):    print ' Say hi ', I-  i in range ( ):    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 from multiprocessing import processfrom multiprocessing import Manager import Time Li = [] def foo (i):    li.append (i)    print ' Say hi ', Li for  i in range:    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 () #方 Law 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

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-*-from multiprocessing import Process, Array, Rlockdef Foo (lock,temp,i):    " "" Add    No. 0 number to "" "    Lock.acquire ()    temp[0] = 100+i for    item in temp:        print I, '-----> ', Item    lock.release () lock = Rlock () temp = Array (' i ', [one-to-one, +,]) for I in range:    p = Process (target=foo,a Rgs= (Lock,temp,i,))    P.start ()

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-process

The 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 ()

 

Gevent
Import 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:

from gevent import Monkey; Monkey.patch_all () Import geventimport urllib2def f (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/'),])

Python: Brief description of threads, processes, and co-routines

Related Article

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.