A Quick look at the most common Multiprocessing commands in Python
Import
from multiprocessing import *
# You can import the following for example: Process, current_process, parent_process, Lock, RLock, cpu_count, Semaphore, Condition, Value, BArrier, Event, set_start_method, etc.
Create Process and run a target function in it
process = Process(target = function_name, args = (arg1,arg2))
Create a Daemon Process
process = Process(daemon = True)
Start a Process
process.start()
Terminate Process
process.terminate()
Kill a Process
process.kill()
Join Process Blocking the Parent process
process.join()
# Asking the Parent process to Wait till the new process finishes
Getting Process PID
process.pid
Number of CPU cores
number_of_cpu_cores = cpu_count()
Get the Parent Process
parent = parent_process()
Get the Current Process
current = current_process()
Get all Child Processes
all_child_processes = active_children()
Get the Current Start Method (whether Spawn, Fork or Forkserver)
start_method = get_start_method()
Get all Start Methods
all_methods = get_all_start_methods()
Set Start Method
set_start_method('spawn')
Create Mutual Exclusion Lock Mutex
mutex_lock = Lock()
mutext_lock.acquire()
#-
#-
#-
mutex_lock.release()
Create Mutex Lock with context manager
mutex_lock = Lock()
with mutex_lock:
#-
#-
#-
Create Re-entrant Mutex Lock
non_mutex_lock = Rlock()
Create Shared Data between Processes
variable = Value(‘i’, 1)
# Shared interger value
array = Array('i', (2, 4, 1, 9, 45, 12))
# Shared integer array
Access Shared Value
data = variable.value
Create Event
event = Event()
Set Event
event.Set()
Waiting (Blocking) for Event to be Set
event.wait()
Create Condition Variable
condition. = Condition()
condition.acquire()
#-
#-
#-
condition.release()
Wait for Condition to be Notified
with condition:
condition.wait()
Create Barrier
barrier = Barrier(5)
Barrier blocking
barrier.wait()
Semaphore
semaphore = Semaphore(5)
# setting number of positions
semaphore.acquire()
#-
#-
#-
semaphore.release()
Create Queue
queue = Queue()
Get Capacity of Queue
cap = queue.qsize()
Add to a Queue
queue.put(item)
Get from Queue
item = queue.get()