3. Multiprocessing

3.1. Problems

  • Zakleszczania

  • Race Condition

3.2. Tworzenie procesów

3.3. Synchronizacja procesów

3.4. IPC - Inter-Process Communication

Aby pickle mógł odtworzyć obiekt, musi posiadać jego definicję - klasę.

Listing 3.26. Klasa Prostokat w module figury
class Prostokat:

    def __init__(self, a, b):
        self.a = float(a)
        self.b = float(b)

    def pole(self):
        return self.a * self.b

    def obwod(self):
        return (self.a + self.b) * 2

    def __str__(self):
        return 'Prostokat(a=%s, b=%s)' % (self.a, self.b)
Listing 3.27. Obiekt wysyłający dane multiprocessing-client.py
from multiprocessing.connection import Client
import logging
import pickle
from book.advanced.src.figury import Prostokat

rectangle = Prostokat(a=5, b=10)
rect = pickle.dumps(rectangle)

address = ('localhost', 6000)
conn = Client(address, authkey=b'secret password')

logging.warning('Sending objects')
conn.send([rect, 'a', 2.5, None, int, sum])

logging.warning('Sending close')
conn.send('close')

conn.close()
Listing 3.28. Obiekt nasłuchujący na połączenia multiprocessing-listener.py
from multiprocessing.connection import Listener
import logging
import pickle

address = ('localhost', 6000)  # family is deduced to be 'AF_INET'

logging.warning('Listening on %s:%s' % address)
listener = Listener(address, authkey=b'secret password')
conn = listener.accept()

logging.warning('connection accepted from %s %s' % listener.last_accepted)

while True:
    msg = conn.recv()
    logging.warning('Received: %s' % msg)

    if msg == 'close':
        conn.close()
        break
    else:
        # do something with msg
        prostokat = pickle.loads(msg[0])
        logging.warning('Prostokat %s' % prostokat)
        print('Pole: %s' % prostokat.pole())

listener.close()

3.5. Zamykanie procesów