


Introduction
The multiprocessing module in Python allows you to create and manage processes, enabling you to take full advantage of multiple processors on a machine. It helps you achieve parallel execution by using separate memory spaces for each process, unlike threading where threads share the same memory space. Here's a list of commonly used classes and methods in the multiprocessing module with brief examples.
1. Process
The Process class is the core of the multiprocessing module, allowing you to create and run new processes.
from multiprocessing import Process def print_numbers(): for i in range(5): print(i) p = Process(target=print_numbers) p.start() # Starts a new process p.join() # Waits for the process to finish
2. start()
Starts the process’s activity.
p = Process(target=print_numbers) p.start() # Runs the target function in a separate process
3. join([timeout])
Blocks the calling process until the process whose join() method is called terminates. Optionally, you can specify a timeout.
p = Process(target=print_numbers) p.start() p.join(2) # Waits up to 2 seconds for the process to finish
4. is_alive()
Returns True if the process is still running.
p = Process(target=print_numbers) p.start() print(p.is_alive()) # True if the process is still running
5. current_process()
Returns the current Process object representing the calling process.
from multiprocessing import current_process def print_current_process(): print(current_process()) p = Process(target=print_current_process) p.start() # Prints the current process info
6. active_children()
Returns a list of all Process objects currently alive.
p1 = Process(target=print_numbers) p2 = Process(target=print_numbers) p1.start() p2.start() print(Process.active_children()) # Lists all active child processes
7. cpu_count()
Returns the number of CPUs available on the machine.
from multiprocessing import cpu_count print(cpu_count()) # Returns the number of CPUs on the machine
8. Pool
A Pool object provides a convenient way to parallelize execution of a function across multiple input values. It manages a pool of worker processes.
from multiprocessing import Pool def square(n): return n * n with Pool(4) as pool: # Pool with 4 worker processes result = pool.map(square, [1, 2, 3, 4, 5]) print(result) # [1, 4, 9, 16, 25]
9. Queue
A Queue is a shared data structure that allows multiple processes to communicate by passing data between them.
from multiprocessing import Process, Queue def put_data(q): q.put([1, 2, 3]) def get_data(q): data = q.get() print(data) q = Queue() p1 = Process(target=put_data, args=(q,)) p2 = Process(target=get_data, args=(q,)) p1.start() p2.start() p1.join() p2.join()
10. Lock
A Lock ensures that only one process can access a shared resource at a time.
from multiprocessing import Process, Lock lock = Lock() def print_numbers(): with lock: for i in range(5): print(i) p1 = Process(target=print_numbers) p2 = Process(target=print_numbers) p1.start() p2.start() p1.join() p2.join()
11. Value and Array
The Value and Array objects allow sharing simple data types and arrays between processes.
from multiprocessing import Process, Value def increment(val): with val.get_lock(): val.value += 1 shared_val = Value('i', 0) processes = [Process(target=increment, args=(shared_val,)) for _ in range(10)] for p in processes: p.start() for p in processes: p.join() print(shared_val.value) # Output will be 10
12. Pipe
A Pipe provides a two-way communication channel between two processes.
from multiprocessing import Process, Pipe def send_message(conn): conn.send("Hello from child") conn.close() parent_conn, child_conn = Pipe() p = Process(target=send_message, args=(child_conn,)) p.start() print(parent_conn.recv()) # Receives data from the child process p.join()
13. Manager
A Manager allows you to create shared objects, such as lists and dictionaries, that multiple processes can modify concurrently.
from multiprocessing import Process, Manager def modify_list(shared_list): shared_list.append("New item") with Manager() as manager: shared_list = manager.list([1, 2, 3]) p = Process(target=modify_list, args=(shared_list,)) p.start() p.join() print(shared_list) # [1, 2, 3, "New item"]
14. Semaphore
A Semaphore allows you to control access to a resource, permitting only a certain number of processes to access it at a time.
from multiprocessing import Process, Semaphore import time sem = Semaphore(2) # Only 2 processes can access the resource def limited_access(): with sem: print("Accessing resource") time.sleep(2) processes = [Process(target=limited_access) for _ in range(5)] for p in processes: p.start() for p in processes: p.join()
Conclusion
The multiprocessing module in Python is designed to take full advantage of multiple processors on a machine. From creating and managing processes using Process, to controlling shared resources with Lock and Semaphore, and facilitating communication through Queue and Pipe, the multiprocessing module is crucial for parallelizing tasks in Python applications.
The above is the detailed content of A Quick Guide to the Python multiprocessing Module with Examples. For more information, please follow other related articles on the PHP Chinese website!

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
