In [1]:
import multiprocessing
def worker():
"""worker function"""
print('Worker')
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
In [2]:
import multiprocessing
import time
def worker():
name = multiprocessing.current_process().name
print(name, 'Starting')
time.sleep(2)
print(name, 'Exiting')
def my_service():
name = multiprocessing.current_process().name
print(name, 'Starting')
time.sleep(3)
print(name, 'Exiting')
if __name__ == '__main__':
service = multiprocessing.Process(
name='my_service',
target=my_service,
)
worker_1 = multiprocessing.Process(
name='worker 1',
target=worker,
)
worker_2 = multiprocessing.Process( # default name
target=worker,
)
worker_1.start()
worker_2.start()
service.start()
In [3]:
import multiprocessing
import time
import sys
def daemon():
p = multiprocessing.current_process()
print('Starting:',p.name, p.pid)
sys.stdout.flush()
time.sleep(2)
print('Exiting:', p.name, p.pid)
sys.stdout.flush()
return
def non_daemon():
p = multiprocessing.current_process()
print('Starting:',p.name,p.pid)
sys.stdout.flush()
print('Exiting:',p.name,p.pid)
sys.stdout.flush()
if __name__ == '__main__':
d = multiprocessing.Process(
name='daemon',target=daemon)
d.daemon=True
n = multiprocessing.Process(
name='non-daemon', target=non_daemon)
n.daemon=False
d.start()
time.sleep(1)
n.start()
In [5]:
import multiprocessing
import time
def slow_worker():
print('Starting worker')
time.sleep(0.1)
print('Fininsh worker')
return
if __name__ == '__main__':
p = multiprocessing.Process(target=slow_worker)
print('Before', p, p.is_alive())
p.start()
print('During',p, p.is_alive())
p.terminate()
print('Terminate:',p, p.is_alive())
p.join()
print('Join', p, p.is_alive())
In [7]:
import multiprocessing
class Worker(multiprocessing.Process):
def run(self):
print('In {}'.format(self.name))
return
if __name__ == '__main__':
jobs = []
for i in range(5):
p = Worker()
jobs.append(p)
p.start()
for j in jobs:
j.join()
In [ ]: