[PYTHON] map

import logging
import multiprocessing
import time

logging.basicConfig(level=logging.DEBUG, format='%(processName)s: %(message)s')


def worker1(i):
    logging.debug('start')
    time.sleep(5)
    logging.debug('end')
    return i * 2


if __name__ == '__main__':
    with multiprocessing.Pool(3) as p:
        r = p.map(worker1, [100, 200])
        logging.debug('excuted map')
        logging.debug(r)

        r = p.map_async(worker1, [100, 200])
        logging.debug('excuted map_async')
        logging.debug(r.get())

        r = p.imap(worker1, [100, 200])
        logging.debug('excuted imap')
        logging.debug([i for i in r])

        #p1 = p.apply_async(worker1, (100,)) #Since it is asynchronous, proceed to the next without waiting for the value to be returned
        #p2 = p.apply_async(worker1, (100,))
        #logging.debug('excuted')
        #logging.debug(p1.get())
        #logging.debug(p2.get())
ForkPoolWorker-1: start
ForkPoolWorker-2: start
ForkPoolWorker-1: end
ForkPoolWorker-2: end
MainProcess: excuted map
MainProcess: [200, 400]
MainProcess: excuted map_async
ForkPoolWorker-1: start
ForkPoolWorker-3: start
ForkPoolWorker-1: end
ForkPoolWorker-3: end
MainProcess: [200, 400]
MainProcess: excuted imap
ForkPoolWorker-2: start
ForkPoolWorker-1: start
ForkPoolWorker-2: end
ForkPoolWorker-1: end
MainProcess: [200, 400]

Recommended Posts