Multiprocessing

 

Code Example


# Multiprocessing


# Way 1

from multiprocessing import Pool
import time

def f(x, y):
for i in range(20):
print(i, end="#")
time.sleep(2)

pool = Pool(processes=10)
for i in range(10):
pool.apply_async(f, [10, i])



# Way 2

import multiprocessing
import os
 
 
def worker1():
    # printing process id
    print("ID of process running worker1: {}".format(os.getpid()))
  
def worker2():
    # printing process id
    print("ID of process running worker2: {}".format(os.getpid()))
 
 
print("ID of main process: {}".format(os.getpid()))
# creating processes
p1 = multiprocessing.Process(target=worker1)
p2 = multiprocessing.Process(target=worker2)
 
# starting processes
p1.start()
p2.start()
 
# process IDs
print("ID of process p1: {}".format(p1.pid))
print("ID of process p2: {}".format(p2.pid))
 


# Way 3

from multiprocessing import Pool
import time
import multiprocessing
import os


def f(x):
for i in range(20):
print(x, end="#")
time.sleep(2)

pool = Pool(processes=10)

for i in range(10):
p1 = multiprocessing.Process(target=f, args=(10, ))
p2 = multiprocessing.Process(target=f, args=(10, ))

for i in range(10):
pool.apply_async(f, [20, ])

p1.start()
p2.start()

print("done")

Comments

Popular posts from this blog

How To Create .ENV File in Python

Create a Large file for Test Data Processing using Python

How to solve the Liner Equation using Python