Python for multi-process

Source: Internet
Author: User

Python can implement multi-threading, but because of the global interpreter Lock (GIL), Python's multithreading can only use one CPU core, that is, only one thread is running at a time, multithreading is just a switch between different threads, and for multicore CPUs, is a huge waste. such as the 4-core CPU, which actually uses only one core, CPU utilization is only 25%. To take full advantage of multicore CPUs, you can implement Python's multi-process.

First, the import-related package:

 from Import Process, Manager Import multiprocessing

Build the process instance and start the process:

p = Process (target = function_name, args = (function_args_list)) P.start ()

where Function_name is the function name of the process run, Function_args_list is the parameter list of the function, it should be noted that the above code must be written in if __name__ = = ' __main__ ': below, otherwise will error.

After the process runs and executes the code behind the parent process, it can be implemented with join ():

P.join ()

If it is more than one process, make sure that multiple processes start () and then join (), otherwise the last process runs out and then begins the next process.

Threads can share data, process is not data sharing, to achieve data sharing, you can use:

M_list = multiprocessing. Manager (). List (list)

The above code shares a list of lists between processes.

Python for multi-process

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.