Getting started with Python concurrency programming

Source: Internet
Author: User

Multi-process

Under Unix/linux, we are provided with an interface similar to the fork () function in the <unistd.h> header file in C, which is located in the OS module, similarly to C, which returns the child process ID for the parent process fork () call, and returns 0 for the child process.

Import OS, timepid = Os.fork () if pid = = 0: While    True:        print ' child process '        time.sleep (1) Else: while    Tru E:        print ' parent process '        time.sleep (3)

Given that Windows does not have this call, Python provides us with a cross-platform version, which is the multiprocessing module that enables cross-platform multi-process through the process class in the Multiprocessing module, which is very simple to use

#coding: Utf-8from multiprocessing import processimport OS, Timedef handler (args):p rint ' process parameter is%s '% Argswhi Le True:print ' child process ' time.sleep (1) If __name__== ' __main__ ':    print ' parent process is%d '% os.getpid ()    Child_proc = Process (target = handler, args= (' Test parameter ',))   #指定子进程开始执行的函数    Child_proc.start ()    while True:        print ' parent process '        time.sleep (3)


Note : If __name__== ' __main__ ' is not added, the code in the module will be executed again after the child process is started, and it should be added to avoid unnecessary errors.

For more convenient use of multiple processes, Python also provides a process pool, located in the multiprocessing module, which is used to pre-allocate processes in conditions that require higher concurrency response, saving the overhead of fork in the process
For more process pool content refer to TCP pre-derived subprocess server in HTTP://BLOG.CSDN.NET/ASPNET_LYC/ARTICLE/DETAILS/38946915#T3

#coding: Utf-8from multiprocessing import Poolimport OS, time, Randomdef handler (Proc_args):    print Proc_argsif __ name__ = = ' __main__ ':    pool = Pool (4)                      #设置进程池中的进程数    for Loop in range (4):p Ool.apply_async (Handler, args= (loop ,))  #apply_async (Func,args) to remove a process from the process pool to execute Func,args as a func parameter. Returns an AsyncResult object that calls the Get () method on the object to obtain the result.    pool.close ()                            #不在往进程池中添加进程    pool.join ()                             #等待所有子进程结束    print ' All child processes done '


Multithreading


Python provides thread and threading modules for multithreading, threading thread is packaged and easier to use, and the Python website is described below

This module provides low-level primitives for working with multiple threads (also called light-weight processes or Tasks) -multiple threads of control sharing their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) is provided. The threading module provides an easier to use and higher-level threading API built on top of this module

Call the Start_new_thread () function in the thread module to generate a new thread

Import Threaddef Thread_handler (args):    print argsif __name__ = = ' __main__ ':    thread.start_new_thread (Thread_ Handler, (' Test parameter ',)) while    True:        Pass


Pass the thread function into and create the thread instance, and then call Start () to create the threads and execute the

Import Threadingdef Thread_handler (args):    print argsif __name__ = = ' __main__ ':    Th1 = Threading. Thread (Target=thread_handler, args= (' Test parameter 1 ',))    Th2 = Threading. Thread (Target=thread_handler, args= (' Test parameter 2 ',))    Th1.start ()    Th2.start ()    th1.join ()    Th2.join ()    print ' All threads ended '




Getting started with Python concurrency programming

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.