Using Multiprocessing in Python
One way to achieve parallelism is to use multi-processing, where we can execute tasks in different cores of the CPU to reduce the total processing time. Python provides the multiprocessing package to facilitate this.
This post summarizes some of the questions I have when I learn to use multiprocessing in Python.
How many processes should we use?
For CPU-bound tasks, set the process number to the number of CPU cores is perhaps appropriate. To get the number of CPUs in your system:
However, the time to complete our task will stop decreasing when the number of processes reach a certain number due to other factors. So it is a good idea to do some benchmark to find the optimal number of processes to use.
Do I need to use pool.close() and pool.join() after finishing my tasks?
pool.close() makes sure that process pool does not accept new processes, and pool.join() waits for the processes to properly finish their work and return. So it is a good idea to use pool.close() and pool.join() explicitly.
Otherwise, the processes may not be released properly. In our application, we have seen error related to memory usage:
OSError: [Errno 12] Cannot allocate memory
Difference between pool.map() and pool.map_aysnc() ?
pool.map is blocking until it gets the actual results, that is, it will block the execution of code until it gets all the result from the processes. pool.map_async , on the other hand, is non-blocking and will return immediately and all we get is an AsyncResult object. To get the actual result, we use result.get() to retrieve them. To illustrate their differences:
If you use p.map() , you will see the following result:
This is because p.map() is blocking. So the statement following it won’t be executed if p.map() hasn’t got the results back.
Unlike p.map , p.map_async is non-blocking. The output for second part of the code is:
That is because p.map_async will not wait for the function to be executed and returned. So you see the output after p.map_async() first. Then you see function gets executed. .
pool.map() without argument?
The function pool.map() is used to feed the element of an iterable to a function one by one. We can not use it to run functions without argument. However, we may change the function to accept an argument and ignore that argument. Or we can write a wrap function to accept argument and invoke the original function in the wrap function.
functions with multiple arguments?
pool.map() can only execute functions that accept one argument, to run a function that accepts multiple arguments, we can use pool.starmap() :
If the other parameters of the function are constants, it may be convenient to use partial functions instead:
Разбираемся с параллельными и конкурентными вычислениями в Python

Я собираюсь рассказать историю о еде, раскрывающую различные возможности конкурентного и параллельного выполнения кода в Python.
Прим. Wunder Fund: для задач, где не критичны экстремально низкие задержки — при сохранении и обработке биржевых данных, мы используем Питон, и естественно применяем описанные в статье подходы. Статья будет полезна начинающим разработчикам.
Мы увидим, что когда один человек одновременно делает несколько дел — это похоже на конкурентность, а когда несколько человек, работая бок о бок, заняты каждый собственным делом — это напоминает параллелизм. Эти ситуации мы разберём на простом и понятном примере закусочных, в которые люди заходят в обеденный перерыв. Такие заведения стремятся обслуживать клиентов как можно быстрее и эффективнее. Потом я покажу реализацию механизмов этих закусочных на Python, а в итоге мы сравним разные возможности одновременного «приготовления нескольких блюд», которые даёт нам этот язык, и разберёмся с тем, в каких ситуациях их применение наиболее оправдано.
А именно, я раскрою здесь следующие вопросы:
Отличия конкурентности от параллелизма.
Различные варианты организации конкурентного выполнения кода (многопоточность, модуль asyncio , модуль multiprocessing , облачные функции) и их сравнение.
Сильные и слабые стороны каждого подхода к организации конкурентного выполнения кода.
Выбор конкретного варианта организации конкурентного выполнения кода с использованием специальной блок-схемы.
В чём отличие между конкурентным и параллельным выполнением кода?
Начнём с определений:
▪ Систему называют конкурентной, если она может поддерживать наличие двух или большего количества действий, находящихся в процессе выполнения в одно и то же время.
▪ Систему называют параллельной, если она может поддерживать наличие двух или большего количества действий, выполняемых в точности в одно и то же время.
Самое главное в этих определениях, их ключевое отличие друг от друга, заключается в словах «в процессе выполнения».
The Art of Concurrency
А теперь перейдём к нашей истории про еду.
В обеденный перерыв вы оказались на улице, на которую раньше не попадали. Там есть два места, где можно перекусить: палатка с надписью «Конкурентные бургеры» и ресторанчик, который называется «Параллельные салаты».
Изделия обоих заведений выглядят завлекательно, правда, перед ними стоят длинные очереди. Поэтому у вас возникает вопрос о том, в каком из них вас обслужат быстрее.
В «Конкурентных бургерах» работает дама среднего возраста. На её руке — татуировка «Python», она во время работы от души хохочет. Она выполняет следующие действия:
Переворачивает жарящиеся котлеты для бургеров.
Накладывает на булочки овощи и котлеты, поливает всё это соусом, выдаёт готовые заказы.
Дама без остановки переключается между этими задачами. Вот она проверяет котлеты на гриле и убирает те, что уже сжарились, потом — принимает заказ, дальше, если есть готовые котлеты, делает бургер, после чего вручает клиенту аппетитный свёрток.
А «Параллельные салаты» укомплектованы командой одинаковых мужчин. На их лицах — дежурные улыбки, во время работы они вежливо переговариваются. Каждый из них делает салат лишь для одного клиента. А именно, каждый принимает заказ, кладёт ингредиенты в чистую миску, добавляет заправку, энергично всё перемешивает, пересыпает получившуюся у него здоровую еду в контейнер, который отдаёт клиенту, а миску отставляет в сторону. А тем временем ещё один работник, такой же, как и остальные, собирает грязные миски и моет их.
Главные различия этих двух заведений заключаются в количестве работников и в том, как именно в них решаются различные задачи:
В «Конкурентных бургерах» одновременно (но не в точности в одно и то же время) выполняется несколько задач. Там имеется единственный работник, который переключается между задачами.
В «Параллельных салатах» несколько задач решается одновременно, в точности в одно и то же время. Здесь имеется несколько работников, каждый из которых в некий момент времени решает лишь одну какую-то задачу.
Вы замечаете, что и там и там клиентов обслуживают с одинаковой скоростью. Женщина в «Конкурентных бургерах» ограничена скоростью, с которой её небольшой гриль способен жарить котлеты. А в «Параллельных салатах» используется труд нескольких мужчин, каждый из которых занят на одном салате и ограничен временем, необходимым на приготовление салата.
Вам становится понятно, что «Конкурентные бургеры» (Concurrent Burgers) ограничены скоростью подсистемы ввода/вывода (I/O bound), а «Параллельные салаты» (Parallel Salads) ограничены возможностями центрального процессора (CPU bound).
Ограничения, связанные с подсистемой ввода/вывода — это когда скорость программы зависит от того, насколько быстро происходит чтение данных с диска или выполнение сетевых запросов. «Подсистемой ввода/вывода» в «Конкурентных бургерах» является процесс приготовления котлет.
Ограничения, связанные с возможностями центрального процессора, ослабляются при повышении быстродействия процессора. Чем он быстрее — тем быстрее работает программа. В «Параллельных салатах» «скорость процессора» — это скорость, с которой сотрудник способен приготовить салат.
Вы не в состоянии принять решение, пять минут пребываете в глубокой задумчивости, а потом ваш товарищ, который уже кое-что знает о «Бургерах» и «Салатах», выводит вас из оцепенения и приглашает вас присоединиться к нему в одной из очередей.
Обратите внимание на то, что «Параллельные салаты» можно назвать и конкурентным и параллельным рестораном. Дело в том, что тут наблюдается «наличие двух или большего количества действий». Параллельное выполнение кода — это разновидность конкурентного выполнения кода.
Эти два заведения помогают осознать суть различия между конкурентным и параллельным выполнением задач. Сейчас мы поговорим о том, как всё это реализуется в Python.
Варианты организации конкурентных вычислений в Python
В Python имеется два механизма, которыми можно воспользоваться для организации конкурентного выполнения кода:
Тут есть и возможность параллельного выполнения кода:
Есть и ещё один вариант организации параллельного выполнения кода, доступный при запуске Python-программ в облачной среде:
Конкурентное выполнение кода на практике
Рассмотрим два возможных варианта реализации «Конкурентных бургеров» с использованием многопоточности и модуля asyncio . В обоих случаях имеется единственный рабочий процесс, который принимает заказы, жарит котлеты и делает бургеры.
И там и там используется лишь один процессор. Он переключается между различными задачами, которые ему нужно решить. Разница между применением многопоточности и модуля asyncio заключается в том, как принимаются решения о смене задач:
При использовании многопоточности операционная система знает о наличии различных потоков и может в любое время прерывать их работу и переключать на другую задачу. Сама программа это не контролирует. Это — то, что называется «вытесняющей многозадачностью» (preemptive multitasking), так как операционная система может принудить поток выполнить переключение на другую задачу. В большинстве языков программирования потоки выполняются параллельно, но в Python в каждый конкретный момент времени позволено выполняться лишь одному потоку.
При использовании модуля asyncio программа сама принимает решение о том, когда ей нужно переключиться между задачами. Каждая задача взаимодействует с другими задачами, передавая им управление тогда, когда она к этому готова. Поэтому такая схема работы называется «кооперативной многозадачностью» (cooperative multitasking), так как каждая задача должна взаимодействовать с другими, передавая им управление в момент, когда она уже не может сделать ничего полезного.
Реализация «Конкурентных бургеров» с использованием многопоточности
При использовании многопоточности рабочий процесс меняет задачи в любой момент выполнения кода. Сам рабочий процесс (в нашем случае — дама средних лет) может находиться в процессе приёма заказа, когда его внезапно отвлекают и предлагают проверить жарящиеся котлеты или сделать бургер, а после этого его могут «переключить» на выполнение любой другой задачи.
Взглянем на «Конкурентные бургеры», реализованные с использованием механизмов многопоточности:
Каждая из задач (принять заказ, пожарить котлету, сделать бургер) представляет собой бесконечный цикл, в котором выполняются соответствующие действия.
В run_concurrent_burger мы запускаем каждую из этих задач в отдельном потоке. Мы можем создать поток для каждой из задач и вручную, но есть гораздо более приятный способ это сделать, который заключается в использовании интерфейса ThreadPoolExecutor , который создаёт поток для каждой переданной ему задачи.
При использовании нескольких потоков мы должны обеспечить такую схему работы с состоянием программы, когда в каждый конкретный момент времени лишь один поток осуществляет чтение или запись данных, к которым могут иметь доступ несколько потоков. Иначе всё может закончиться ситуацией, когда два потока «схватят» одну и ту же котлету, что может очень раздосадовать клиента. Существует такое понятие, как «потокобезопасность» (thread safety), которое имеет отношение к этому вопросу.
Для того чтобы обеспечить безопасную работу потоков мы используем очереди (Queues), позволяющие передавать управление состоянием программы между потоками. В пределах отдельных задач очередь блокируется при вызове get до тех пор, пока мы не обслужим клиента, не выполним заказ или не сжарим котлету. Операционная система не пытается переключиться на заблокированный поток, что даёт нам безопасный способ передачи состояния между потоками. Поток, помещая состояние в очередь, не использует его, а затем сообщает о том, что, в процессе его использования, не будет его менять.
Сильные стороны многопоточности
Операции ввода/вывода не останавливают выполнение других задач.
Отличная поддержка различными версиями Python и библиотеками — если нечто может быть запущено в однопоточном режиме — весьма вероятно то, что это заработает и в многопоточном режиме.
Слабые стороны многопоточности
Система работает медленнее, чем при применении модуля asyncio из-за того, что на неё ложится дополнительная нагрузка по переключению между системными потоками.
Не обеспечивается потокобезопасность.
Не ускоряется выполнение задач, зависящих от скорости центрального процессора, наподобие задачи по изготовлению салатов (это — из-за того, что Python поддерживает выполнение в каждый конкретный момент времени лишь одного потока). В результате один работник, одновременно готовящий несколько салатов, не сделает их быстрее, чем если бы делал их один за другим. Дело в том, что в итоге на приготовление одного салата при одновременном приготовлении нескольких салатов уйдёт столько же времени, сколько ушло бы, если салаты готовились бы по одному.
Реализация «Конкурентных бургеров» с использованием модуля asyncio
При использовании модуля asyncio имеется единственный цикл событий, который занимается управлением всеми задачами. Задачи могут пребывать в некотором количестве различных состояний, самыми важными из которых можно назвать состояние готовности (ready) и состояние ожидания (waiting). Цикл событий на каждой итерации проверяет, имеются ли задачи, пребывающие в состоянии ожидания, которые завершены и оказались в состоянии готовности. Затем цикл берёт задачу, находящуюся в состоянии готовности, и выполняет её до тех пор, пока она не завершится, либо — до тех пор, пока не окажется, что ей нужно дождаться завершения другой задачи. Часто подобные задачи представлены операциями ввода/вывода наподобие чтения данных с диска или выполнения HTTP-запроса.
Есть пара ключевых слов, которые используются в большинстве вариантов применения asyncio . Это — async и await .
Ключевое слово async используется при объявлении функций для указания на то, что эти функции нужно запускать в виде отдельных задач.
Ключевое слово await позволяет создавать новые задачи и передавать управление циклу событий. Это ключевое слово позволяет перевести задачу в состояние ожидания. После завершения новой задачи она оказывается в состоянии готовности.
Посмотрим на реализацию «Конкурентных бургеров» с использованием модуля asyncio :
Каждая из функций, олицетворяющих задачи приёма заказа, поджаривания котлеты и приготовления бургера, объявлена с использованием конструкции async def .
В пределах этих задач работник переключается на новую задачу каждый раз, когда используется ключевое слово await . А именно, это происходит в следующих ситуациях:
В задаче приёма заказа:
В задаче поджаривания котлет:
В задаче изготовления бургеров:
Последний кусок этой головоломки заключается в функции run_concurrent_burger , в которой вызывается asyncio.gather для планирования задач, которые должны быть запущены циклом событий, представленным работником «Конкурентных бургеров».
Как мы уже знаем, в точности тогда, когда осуществляется переключение задач, нам не нужно заботиться об управлении совместным доступом к состоянию программы. Мы можем это реализовать, всего лишь воспользовавшись списком очередей и зная то, что у нас не возникнет ситуации, когда две задачи случайно «ухватятся» за одну котлету. Но для решения подобных задач настоятельно рекомендуется пользоваться очередями asyncio , так как это позволит нам очень просто наладить взаимодействие между задачами, указывая на особые моменты в процессах выполнения задач, в которые их можно приостанавливать.
Одним из интересных аспектов использования модуля asyncio является то, что ключевое слово async меняет интерфейс функции, что приводит к невозможности вызова таких функций из обычных функций, не являющихся асинхронными. Это можно счесть как неудачным, так и удачным решением. С одной стороны, можно сказать, что это вредит возможностям по композиции функций, так как нельзя смешивать asyncio -функции с функциями обычными. А с другой стороны, если возможности asyncio используются лишь для организации операций ввода/вывода, это заставляет программиста чётко разделять логику ввода/вывода и бизнес-логику приложения, ограничивая применение asyncio теми частями приложения, которые взаимодействуют с внешним миром, делая код понятнее, упрощая его тестирование. Явное выделение операций, отвечающих за ввод/вывод данных — это довольно-таки распространённая практика в типизированных функциональных языках, а в Haskell это обязательно.
Сильные стороны применения модуля asyncio
Обеспечение чрезвычайно высокой скорости работы при решении задач, зависящих от подсистемы ввода/вывода.
Слабые стороны применения модуля asyncio
Задачи, производительность которых зависит от процессора, не ускоряются.
Этот модуль появился в Python сравнительно недавно.
Параллельное выполнение кода на практике
В ресторанчике «Параллельные салаты» есть несколько работников, которые делают салаты (все разом). Мы собираемся создать реализацию этого заведения с использованием модуля multiprocessing .
А потом мы ещё заглянем в кофейню, называемую «Облачный кофе» и взглянем на то, как для параллельного выполнения задач можно использовать облачные функции.
Реализация «Параллельных салатов» с использованием модуля multiprocessing
Механизм работы «Параллельных салатов» отлично демонстрирует возможности модуля multiprocessing .
Каждый работник в этом заведении представлен новым процессом, создаваемым операционной системой. Эти процессы создаются посредством класса ProcessPoolExecutor , который назначает каждому из них задачи.
При использовании модуля multiprocessing каждая задача выполняется в отдельном процессе. Эти процессы параллельно и независимо друг от друга выполняются операционной системой и друг друга не блокируют. Количество процессов, которые реально можно выполнять параллельно, ограничено количеством ядер процессора. Поэтому мы ограничим соответствующим числом количество сотрудников ресторана, которые делают салаты.
Так как наши задачи выполняются в различных процессах — они не используют какое-либо обычное состояние Python-программы совместно. У каждого из процессов имеется независимая копия всего состояния программы. Для налаживания «общения» процессов необходимо использовать специальные очереди, поддерживаемые модулем multiprocessing .
Попутная заметка: модули asyncio и multiprocessing
Один из сценариев использования модуля multiprocessing заключается в том, чтобы снимать нагрузку, связанную с выполнением тяжёлых вычислительных задач, с asyncio -приложений, чтобы такие задачи не блокировали бы другие части приложения. Вот небольшой набросок, иллюстрирующий этот сценарий:
Сильные стороны применения модуля multiprocessing
Ускорение задач, скорость выполнения которых ограничена возможностями процессора.
Этот модуль может быть использован для организации длительных вычислений, выполняемых на веб-серверах в отдельных процессах.
Слабые стороны применения модуля multiprocessing
Отсутствует механизм совместного использования ресурсов.
Создаётся большая дополнительная нагрузка на систему. Этот модуль не рекомендуется использовать в задачах, скорость выполнения которых привязана к подсистеме ввода/вывода.
Реализация «Облачного кофе» с использованием облачных функций
Вы с другом пошли в парк, чтобы съесть то, что удалось раздобыть на обед, и заметили пушистое разноцветное облако, висящее над группой людей. Вы присмотрелись и поняли, что это — вывеска кофейни «Облачный кофе».
Ваш друг кофе не выносит, но вы, всё же, вместе решили взять по стаканчику — так сказать, забавы ради. Когда вы подошли к кофейне, каждый из вас попал за собственную стойку со своим баристой, которые медленно выплыли из облака. Баристы приняли у вас заказы, сделали кофе и подали его вам и вашему другу.
Вдруг в «Облачный кофе» влетела оживлённая толпа народа. Стоек на всех не хватило, но совсем скоро из облака выплыли новые стойки с баристами, после чего всех, кто хотел выпить кофе, быстро обслужили. Когда народ попил кофе и дополнительные стойки опустели, эти стойки ещё немного постояли (баристы совершенно не обращали внимания на другие стойки) после чего уплыли обратно в облако.
Когда вы попили кофе и вышли — вы обратили внимание на то, что в кофейне всегда находится примерно одинаковое количество стоек, так как туда постоянно подходят люди, делающие заказы. Если в кофейне оказывается больше людей, чем обычно, из облака выплывают новые стойки, а когда случается так, что заказ выполнен, клиент ушёл, а стойка оказалась никому не нужной, она ещё немного пустует, а потом возвращается в облако.
Ваш друг решил сделать абсурдно сложный заказ, чтобы попробовать что-то новое, такое, в чём что-то перебьёт вкус обычного кофе, но заказа он так и не дождался. Бариста добавлял в напиток зефир и шоколадные стружки, но вдруг бросил всё в корзину и крикнул: «Тайм-аут».
Вы, оба на грани нервного срыва, пошли прочь из парка.
Облачные функции — это ещё один механизм ускорения работы кода, на который стоит обратить внимание тем, кто занимается разработкой веб-сервисов. Их, пожалуй, писать легче всего, так как каждая из них отвечает лишь за выполнение отдельного «заказа» за один раз. Применяя их, можно совершенно забыть о конкурентности и о прочих подобных вещах.
Каждый запрос обслуживается отдельным экземпляром всего приложения. Когда создаётся новый экземпляр приложения — имеется небольшая задержка, связанная с выделением ресурсов и запуском этого экземпляра приложения. Именно поэтому экземпляры приложения могут какое-то время простаивать, ожидая поступления новых запросов. Запросы, если они поступают уже запущенному экземпляру приложения, могут быть выполнены практически мгновенно, без задержек. А вот после того, как новых запросов некоторое время не поступает — бездействующие экземпляры приложения уничтожаются, ресурсы, занятые ими, возвращаются системе.
Обработка каждого запроса через некоторое время, зависящее от реализации системы, завершается по тайм-ауту. Нужно обеспечить, чтобы задачи завершались бы до наступления этого тайм-аута, или они будут попросту исчезать, так и не выполнившись.
Экземпляры приложения не могут взаимодействовать с другими экземплярами приложения. Они ни при каких условиях не должны хранить состояние приложения между вызовами, так как они могут быть когда угодно уничтожены.
Наиболее известные реализации этого механизма представлены такими платформами, как AWS Lambda, Azure Functions и Google Cloud Functions.
Сильные стороны облачных функций
Чрезвычайно простая модель организации вычислений.
Их использование может быть дешевле, чем применение постоянно работающего сервера.
Весьма лёгкое масштабирование систем, основанных на таких функциях.
Слабые стороны облачных функций
При запуске новых экземпляров приложений могут наблюдаться задержки.
Время выполнения вычислений, связанных с запросами, ограничено тайм-аутами.
У разработчика нет полного контроля над используемой версией Python — можно использовать лишь те версии, которые предоставлены облачным провайдером.
Какой вариант конкурентного выполнения кода выбрать?
Давайте сведём всё, о чём мы говорили, в единую таблицу.
Многопоточность
Модуль asyncio
Модуль multithreading
Облачные функции
Использование нескольких экземпляров приложения
Конкурентное или параллельное выполнение кода
Возможность самостоятельного управления конкурентностью
Принятие решения о переключении между задачами
Операционная система сама выбирает момент переключения между задачами
Задача принимает решение о том, когда ей нужно передать управление другой сущности
Процессы выполняются одновременно, на разных ядрах процессора
Запросы выполняются одновременно в различных экземплярах приложения
Максимальное количество параллельно выполняемых процессов
Соответствует количеству ядер процессора
Взаимодействие между задачами
Многопроцессные очереди и возвращаемые значения
Задачи, которые решают с помощью данного подхода
Те, производительность которых ограничена подсистемой ввода/вывода
Те, производительность которых ограничена подсистемой ввода/вывода
Те, производительность которых ограничена возможностями процессора
Те, производительность которых ограничена подсистемой ввода/вывода в том случае, если они выполняются быстрее, чем истекает тайм-аут (около 5 минут)
Дополнительная нагрузка на систему
Использование одного системного потока для решения задач означает необходимость в оперативной памяти и увеличивает время переключения между задачами
Максимально низкая, все задачи выполняются в одном процессе и в одном потоке
Использование отдельного системного процесса на каждую задачу приводит к потреблению памяти, превышающему то, что характерно для многопоточных систем
При запуске новых экземпляров приложения наблюдаются задержки
Теперь, когда вы видите общую картину, вы без труда подберёте именно то, что вам нужно.
Но, правда, прежде чем делать окончательный выбор, нужно как следует подумать о самой необходимости ускорения задач. Если некая задача запускается раз в неделю, а на её выполнение нужно 10 минут — есть ли смысл в её ускорении?
Если же вы выяснили, что смысл в ускорении какой-то задачи определённо есть, можете воспользоваться следующей блок-схемой для того, чтобы точно определиться с выбором подхода к её выполнению, который подойдёт именно вам.

Итоги
Мы рассмотрели различные варианты организации конкурентного выполнения кода в Python:
Использование модуля asyncio .
Использование модуля multiprocessing .
Мы, кроме того, уделили некоторое внимание одной из возможностей развёртывания приложений, использование которой упрощает параллельное выполнение Python-кода:
Теперь вы знакомы с особенностями этих подходов к написанию программ и с их сильными и слабыми сторонами, знаете о том, для решения каких задач они подходят лучше всего.
О, а приходите к нам работать?
Мы в wunderfund.io занимаемся высокочастотной алготорговлей с 2014 года. Высокочастотная торговля — это непрерывное соревнование лучших программистов и математиков всего мира. Присоединившись к нам, вы станете частью этой увлекательной схватки.
Мы предлагаем интересные и сложные задачи по анализу данных и low latency разработке для увлеченных исследователей и программистов. Гибкий график и никакой бюрократии, решения быстро принимаются и воплощаются в жизнь.
Сейчас мы ищем плюсовиков, питонистов, дата-инженеров и мл-рисерчеров.
Присоединяйтесь к нашей команде.
multiprocessing — Process-based parallelism¶
This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi . See WebAssembly platforms for more information.
Introduction¶
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
The multiprocessing module also introduces APIs which do not have analogs in the threading module. A prime example of this is the Pool object which offers a convenient means of parallelizing the execution of a function across multiple input values, distributing the input data across processes (data parallelism). The following example demonstrates the common practice of defining such functions in a module so that child processes can successfully import that module. This basic example of data parallelism using Pool ,
will print to standard output
concurrent.futures.ProcessPoolExecutor offers a higher level interface to push tasks to a background process without blocking execution of the calling process. Compared to using the Pool interface directly, the concurrent.futures API more readily allows the submission of work to the underlying process pool to be separated from waiting for the results.
The Process class¶
In multiprocessing , processes are spawned by creating a Process object and then calling its start() method. Process follows the API of threading.Thread . A trivial example of a multiprocess program is
To show the individual process IDs involved, here is an expanded example:
For an explanation of why the if __name__ == ‘__main__’ part is necessary, see Programming guidelines .
Contexts and start methods¶
Depending on the platform, multiprocessing supports three ways to start a process. These start methods are
spawn
The parent process starts a fresh Python interpreter process. The child process will only inherit those resources necessary to run the process object’s run() method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using fork or forkserver.
Available on Unix and Windows. The default on Windows and macOS.
fork
The parent process uses os.fork() to fork the Python interpreter. The child process, when it begins, is effectively identical to the parent process. All resources of the parent are inherited by the child process. Note that safely forking a multithreaded process is problematic.
Available on Unix only. The default on Unix.
forkserver
When the program starts and selects the forkserver start method, a server process is started. From then on, whenever a new process is needed, the parent process connects to the server and requests that it fork a new process. The fork server process is single threaded so it is safe for it to use os.fork() . No unnecessary resources are inherited.
Available on Unix platforms which support passing file descriptors over Unix pipes.
Changed in version 3.8: On macOS, the spawn start method is now the default. The fork start method should be considered unsafe as it can lead to crashes of the subprocess. See bpo-33725.
Changed in version 3.4: spawn added on all Unix platforms, and forkserver added for some Unix platforms. Child processes no longer inherit all of the parents inheritable handles on Windows.
On Unix using the spawn or forkserver start methods will also start a resource tracker process which tracks the unlinked named system resources (such as named semaphores or SharedMemory objects) created by processes of the program. When all processes have exited the resource tracker unlinks any remaining tracked object. Usually there should be none, but if a process was killed by a signal there may be some “leaked” resources. (Neither leaked semaphores nor shared memory segments will be automatically unlinked until the next reboot. This is problematic for both objects because the system allows only a limited number of named semaphores, and shared memory segments occupy some space in the main memory.)
To select a start method you use the set_start_method() in the if __name__ == ‘__main__’ clause of the main module. For example:
set_start_method() should not be used more than once in the program.
Alternatively, you can use get_context() to obtain a context object. Context objects have the same API as the multiprocessing module, and allow one to use multiple start methods in the same program.
Note that objects related to one context may not be compatible with processes for a different context. In particular, locks created using the fork context cannot be passed to processes started using the spawn or forkserver start methods.
A library which wants to use a particular start method should probably use get_context() to avoid interfering with the choice of the library user.
The ‘spawn’ and ‘forkserver’ start methods cannot currently be used with “frozen” executables (i.e., binaries produced by packages like PyInstaller and cx_Freeze) on Unix. The ‘fork’ start method does work.
Exchanging objects between processes¶
multiprocessing supports two types of communication channel between processes:
Queues
The Queue class is a near clone of queue.Queue . For example:
Queues are thread and process safe.
Pipes
The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way). For example:
The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv() methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.
Synchronization between processes¶
multiprocessing contains equivalents of all the synchronization primitives from threading . For instance one can use a lock to ensure that only one process prints to standard output at a time:
Without using the lock output from the different processes is liable to get all mixed up.
Sharing state between processes¶
As mentioned above, when doing concurrent programming it is usually best to avoid using shared state as far as possible. This is particularly true when using multiple processes.
However, if you really do need to use some shared data then multiprocessing provides a couple of ways of doing so.
Shared memory
Data can be stored in a shared memory map using Value or Array . For example, the following code
The ‘d’ and ‘i’ arguments used when creating num and arr are typecodes of the kind used by the array module: ‘d’ indicates a double precision float and ‘i’ indicates a signed integer. These shared objects will be process and thread-safe.
For more flexibility in using shared memory one can use the multiprocessing.sharedctypes module which supports the creation of arbitrary ctypes objects allocated from shared memory.
Server process
A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager() will support types list , dict , Namespace , Lock , RLock , Semaphore , BoundedSemaphore , Condition , Event , Barrier , Queue , Value and Array . For example,
Server process managers are more flexible than using shared memory objects because they can be made to support arbitrary object types. Also, a single manager can be shared by processes on different computers over a network. They are, however, slower than using shared memory.
Using a pool of workers¶
The Pool class represents a pool of worker processes. It has methods which allows tasks to be offloaded to the worker processes in a few different ways.
Note that the methods of a pool should only ever be used by the process which created it.
Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.pool.Pool examples will not work in the interactive interpreter. For example:
(If you try this it will actually output three full tracebacks interleaved in a semi-random fashion, and then you may have to stop the parent process somehow.)
Reference¶
The multiprocessing package mostly replicates the API of the threading module.
Process and exceptions¶
Process objects represent activity that is run in a separate process. The Process class has equivalents of all the methods of threading.Thread .
The constructor should always be called with keyword arguments. group should always be None ; it exists solely for compatibility with threading.Thread . target is the callable object to be invoked by the run() method. It defaults to None , meaning nothing is called. name is the process name (see name for more details). args is the argument tuple for the target invocation. kwargs is a dictionary of keyword arguments for the target invocation. If provided, the keyword-only daemon argument sets the process daemon flag to True or False . If None (the default), this flag will be inherited from the creating process.
By default, no arguments are passed to target. The args argument, which defaults to () , can be used to specify a list or tuple of the arguments to pass to target.
If a subclass overrides the constructor, it must make sure it invokes the base class constructor ( Process.__init__() ) before doing anything else to the process.
Changed in version 3.3: Added the daemon argument.
Method representing the process’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
Using a list or tuple as the args argument passed to Process achieves the same effect.
Start the process’s activity.
This must be called at most once per process object. It arranges for the object’s run() method to be invoked in a separate process.
If the optional argument timeout is None (the default), the method blocks until the process whose join() method is called terminates. If timeout is a positive number, it blocks at most timeout seconds. Note that the method returns None if its process terminates or if the method times out. Check the process’s exitcode to determine if it terminated.
A process can be joined many times.
A process cannot join itself because this would cause a deadlock. It is an error to attempt to join a process before it has been started.
The process’s name. The name is a string used for identification purposes only. It has no semantics. Multiple processes may be given the same name.
The initial name is set by the constructor. If no explicit name is provided to the constructor, a name of the form ‘Process-N1:N2:…:Nk’ is constructed, where each Nk is the N-th child of its parent.
Return whether the process is alive.
Roughly, a process object is alive from the moment the start() method returns until the child process terminates.
The process’s daemon flag, a Boolean value. This must be set before start() is called.
The initial value is inherited from the creating process.
When a process exits, it attempts to terminate all of its daemonic child processes.
Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited.
In addition to the threading.Thread API, Process objects also support the following attributes and methods:
Return the process ID. Before the process is spawned, this will be None .
The child’s exit code. This will be None if the process has not yet terminated.
If the child’s run() method returned normally, the exit code will be 0. If it terminated via sys.exit() with an integer argument N, the exit code will be N.
If the child terminated due to an exception not caught within run() , the exit code will be 1. If it was terminated by signal N, the exit code will be the negative value -N.
The process’s authentication key (a byte string).
When multiprocessing is initialized the main process is assigned a random string using os.urandom() .
When a Process object is created, it will inherit the authentication key of its parent process, although this may be changed by setting authkey to another byte string.
A numeric handle of a system object which will become “ready” when the process ends.
You can use this value if you want to wait on several events at once using multiprocessing.connection.wait() . Otherwise calling join() is simpler.
On Windows, this is an OS handle usable with the WaitForSingleObject and WaitForMultipleObjects family of API calls. On Unix, this is a file descriptor usable with primitives from the select module.
New in version 3.3.
Terminate the process. On Unix this is done using the SIGTERM signal; on Windows TerminateProcess() is used. Note that exit handlers and finally clauses, etc., will not be executed.
Note that descendant processes of the process will not be terminated – they will simply become orphaned.
If this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process. Similarly, if the process has acquired a lock or semaphore etc. then terminating it is liable to cause other processes to deadlock.
Same as terminate() but using the SIGKILL signal on Unix.
New in version 3.7.
Close the Process object, releasing all resources associated with it. ValueError is raised if the underlying process is still running. Once close() returns successfully, most other methods and attributes of the Process object will raise ValueError .
New in version 3.7.
Note that the start() , join() , is_alive() , terminate() and exitcode methods should only be called by the process that created the process object.
Example usage of some of the methods of Process :
The base class of all multiprocessing exceptions.
exception multiprocessing. BufferTooShort ¶
Exception raised by Connection.recv_bytes_into() when the supplied buffer object is too small for the message read.
If e is an instance of BufferTooShort then e.args[0] will give the message as a byte string.
exception multiprocessing. AuthenticationError ¶
Raised when there is an authentication error.
exception multiprocessing. TimeoutError ¶
Raised by methods with a timeout when the timeout expires.
Pipes and Queues¶
When using multiple processes, one generally uses message passing for communication between processes and avoids having to use any synchronization primitives like locks.
For passing messages one can use Pipe() (for a connection between two processes) or a queue (which allows multiple producers and consumers).
The Queue , SimpleQueue and JoinableQueue types are multi-producer, multi-consumer FIFO queues modelled on the queue.Queue class in the standard library. They differ in that Queue lacks the task_done() and join() methods introduced into Python 2.5’s queue.Queue class.
If you use JoinableQueue then you must call JoinableQueue.task_done() for each task removed from the queue or else the semaphore used to count the number of unfinished tasks may eventually overflow, raising an exception.
Note that one can also create a shared queue by using a manager object – see Managers .
multiprocessing uses the usual queue.Empty and queue.Full exceptions to signal a timeout. They are not available in the multiprocessing namespace so you need to import them from queue .
When an object is put on a queue, the object is pickled and a background thread later flushes the pickled data to an underlying pipe. This has some consequences which are a little surprising, but should not cause any practical difficulties – if they really bother you then you can instead use a queue created with a manager .
After putting an object on an empty queue there may be an infinitesimal delay before the queue’s empty() method returns False and get_nowait() can return without raising queue.Empty .
If multiple processes are enqueuing objects, it is possible for the objects to be received at the other end out-of-order. However, objects enqueued by the same process will always be in the expected order with respect to each other.
If a process is killed using Process.terminate() or os.kill() while it is trying to use a Queue , then the data in the queue is likely to become corrupted. This may cause any other process to get an exception when it tries to use the queue later on.
As mentioned above, if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread ), then that process will not terminate until all buffered items have been flushed to the pipe.
This means that if you try joining that process you may get a deadlock unless you are sure that all items which have been put on the queue have been consumed. Similarly, if the child process is non-daemonic then the parent process may hang on exit when it tries to join all its non-daemonic children.
Note that a queue created using a manager does not have this issue. See Programming guidelines .
For an example of the usage of queues for interprocess communication see Examples .
multiprocessing. Pipe ( [ duplex ] ) ¶
Returns a pair (conn1, conn2) of Connection objects representing the ends of a pipe.
If duplex is True (the default) then the pipe is bidirectional. If duplex is False then the pipe is unidirectional: conn1 can only be used for receiving messages and conn2 can only be used for sending messages.
class multiprocessing. Queue ( [ maxsize ] ) ¶
Returns a process shared queue implemented using a pipe and a few locks/semaphores. When a process first puts an item on the queue a feeder thread is started which transfers objects from a buffer into the pipe.
The usual queue.Empty and queue.Full exceptions from the standard library’s queue module are raised to signal timeouts.
Queue implements all the methods of queue.Queue except for task_done() and join() .
Return the approximate size of the queue. Because of multithreading/multiprocessing semantics, this number is not reliable.
Note that this may raise NotImplementedError on Unix platforms like macOS where sem_getvalue() is not implemented.
Return True if the queue is empty, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.
Return True if the queue is full, False otherwise. Because of multithreading/multiprocessing semantics, this is not reliable.
Put obj into the queue. If the optional argument block is True (the default) and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the queue.Full exception if no free slot was available within that time. Otherwise (block is False ), put an item on the queue if a free slot is immediately available, else raise the queue.Full exception (timeout is ignored in that case).
Changed in version 3.8: If the queue is closed, ValueError is raised instead of AssertionError .
Equivalent to put(obj, False) .
Remove and return an item from the queue. If optional args block is True (the default) and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the queue.Empty exception if no item was available within that time. Otherwise (block is False ), return an item if one is immediately available, else raise the queue.Empty exception (timeout is ignored in that case).
Changed in version 3.8: If the queue is closed, ValueError is raised instead of OSError .
Equivalent to get(False) .
multiprocessing.Queue has a few additional methods not found in queue.Queue . These methods are usually unnecessary for most code:
Indicate that no more data will be put on this queue by the current process. The background thread will quit once it has flushed all buffered data to the pipe. This is called automatically when the queue is garbage collected.
Join the background thread. This can only be used after close() has been called. It blocks until the background thread exits, ensuring that all data in the buffer has been flushed to the pipe.
By default if a process is not the creator of the queue then on exit it will attempt to join the queue’s background thread. The process can call cancel_join_thread() to make join_thread() do nothing.
Prevent join_thread() from blocking. In particular, this prevents the background thread from being joined automatically when the process exits – see join_thread() .
A better name for this method might be allow_exit_without_flush() . It is likely to cause enqueued data to be lost, and you almost certainly will not need to use it. It is really only there if you need the current process to exit immediately without waiting to flush enqueued data to the underlying pipe, and you don’t care about lost data.
This class’s functionality requires a functioning shared semaphore implementation on the host operating system. Without one, the functionality in this class will be disabled, and attempts to instantiate a Queue will result in an ImportError . See bpo-3770 for additional information. The same holds true for any of the specialized queue types listed below.
It is a simplified Queue type, very close to a locked Pipe .
Close the queue: release internal resources.
A queue must not be used anymore after it is closed. For example, get() , put() and empty() methods must no longer be called.
New in version 3.9.
Return True if the queue is empty, False otherwise.
Remove and return an item from the queue.
Put item into the queue.
class multiprocessing. JoinableQueue ( [ maxsize ] ) ¶
JoinableQueue , a Queue subclass, is a queue which additionally has task_done() and join() methods.
Indicate that a formerly enqueued task is complete. Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items placed in the queue.
Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
Miscellaneous¶
Return list of all live children of the current process.
Calling this has the side effect of “joining” any processes which have already finished.
Return the number of CPUs in the system.
This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0))
When the number of CPUs cannot be determined a NotImplementedError is raised.
Return the Process object corresponding to the current process.
Return the Process object corresponding to the parent process of the current_process() . For the main process, parent_process will be None .
New in version 3.8.
Add support for when a program which uses multiprocessing has been frozen to produce a Windows executable. (Has been tested with py2exe, PyInstaller and cx_Freeze.)
One needs to call this function straight after the if __name__ == ‘__main__’ line of the main module. For example:
If the freeze_support() line is omitted then trying to run the frozen executable will raise RuntimeError .
Calling freeze_support() has no effect when invoked on any operating system other than Windows. In addition, if the module is being run normally by the Python interpreter on Windows (the program has not been frozen), then freeze_support() has no effect.
Returns a list of the supported start methods, the first of which is the default. The possible start methods are ‘fork’ , ‘spawn’ and ‘forkserver’ . On Windows only ‘spawn’ is available. On Unix ‘fork’ and ‘spawn’ are always supported, with ‘fork’ being the default.
New in version 3.4.
Return a context object which has the same attributes as the multiprocessing module.
If method is None then the default context is returned. Otherwise method should be ‘fork’ , ‘spawn’ , ‘forkserver’ . ValueError is raised if the specified start method is not available.
New in version 3.4.
Return the name of start method used for starting processes.
If the start method has not been fixed and allow_none is false, then the start method is fixed to the default and the name is returned. If the start method has not been fixed and allow_none is true then None is returned.
The return value can be ‘fork’ , ‘spawn’ , ‘forkserver’ or None . ‘fork’ is the default on Unix, while ‘spawn’ is the default on Windows and macOS.
Changed in version 3.8: On macOS, the spawn start method is now the default. The fork start method should be considered unsafe as it can lead to crashes of the subprocess. See bpo-33725.
New in version 3.4.
Set the path of the Python interpreter to use when starting a child process. (By default sys.executable is used). Embedders will probably need to do some thing like
before they can create child processes.
Changed in version 3.4: Now supported on Unix when the ‘spawn’ start method is used.
Changed in version 3.11: Accepts a path-like object .
Set the method which should be used to start child processes. The method argument can be ‘fork’ , ‘spawn’ or ‘forkserver’ . Raises RuntimeError if the start method has already been set and force is not True . If method is None and force is True then the start method is set to None . If method is None and force is False then the context is set to the default context.
Note that this should be called at most once, and it should be protected inside the if __name__ == ‘__main__’ clause of the main module.
New in version 3.4.
Connection Objects¶
Connection objects allow the sending and receiving of picklable objects or strings. They can be thought of as message oriented connected sockets.
Connection objects are usually created using Pipe – see also Listeners and Clients .
class multiprocessing.connection. Connection ¶ send ( obj ) ¶
Send an object to the other end of the connection which should be read using recv() .
The object must be picklable. Very large pickles (approximately 32 MiB+, though it depends on the OS) may raise a ValueError exception.
Return an object sent from the other end of the connection using send() . Blocks until there is something to receive. Raises EOFError if there is nothing left to receive and the other end was closed.
Return the file descriptor or handle used by the connection.
Close the connection.
This is called automatically when the connection is garbage collected.
Return whether there is any data available to be read.
If timeout is not specified then it will return immediately. If timeout is a number then this specifies the maximum time in seconds to block. If timeout is None then an infinite timeout is used.
Note that multiple connection objects may be polled at once by using multiprocessing.connection.wait() .
Send byte data from a bytes-like object as a complete message.
If offset is given then data is read from that position in buffer. If size is given then that many bytes will be read from buffer. Very large buffers (approximately 32 MiB+, though it depends on the OS) may raise a ValueError exception
Return a complete message of byte data sent from the other end of the connection as a string. Blocks until there is something to receive. Raises EOFError if there is nothing left to receive and the other end has closed.
If maxlength is specified and the message is longer than maxlength then OSError is raised and the connection will no longer be readable.
Changed in version 3.3: This function used to raise IOError , which is now an alias of OSError .
Read into buffer a complete message of byte data sent from the other end of the connection and return the number of bytes in the message. Blocks until there is something to receive. Raises EOFError if there is nothing left to receive and the other end was closed.
buffer must be a writable bytes-like object . If offset is given then the message will be written into the buffer from that position. Offset must be a non-negative integer less than the length of buffer (in bytes).
If the buffer is too short then a BufferTooShort exception is raised and the complete message is available as e.args[0] where e is the exception instance.
Changed in version 3.3: Connection objects themselves can now be transferred between processes using Connection.send() and Connection.recv() .
New in version 3.3: Connection objects now support the context management protocol – see Context Manager Types . __enter__() returns the connection object, and __exit__() calls close() .
The Connection.recv() method automatically unpickles the data it receives, which can be a security risk unless you can trust the process which sent the message.
Therefore, unless the connection object was produced using Pipe() you should only use the recv() and send() methods after performing some sort of authentication. See Authentication keys .
If a process is killed while it is trying to read or write to a pipe then the data in the pipe is likely to become corrupted, because it may become impossible to be sure where the message boundaries lie.
Synchronization primitives¶
Generally synchronization primitives are not as necessary in a multiprocess program as they are in a multithreaded program. See the documentation for threading module.
Note that one can also create synchronization primitives by using a manager object – see Managers .
class multiprocessing. Barrier ( parties [ , action [ , timeout ] ] ) ¶
A barrier object: a clone of threading.Barrier .
New in version 3.3.
A bounded semaphore object: a close analog of threading.BoundedSemaphore .
A solitary difference from its close analog exists: its acquire method’s first argument is named block, as is consistent with Lock.acquire() .
On macOS, this is indistinguishable from Semaphore because sem_getvalue() is not implemented on that platform.
A condition variable: an alias for threading.Condition .
If lock is specified then it should be a Lock or RLock object from multiprocessing .
Changed in version 3.3: The wait_for() method was added.
class multiprocessing. Lock ¶
A non-recursive lock object: a close analog of threading.Lock . Once a process or thread has acquired a lock, subsequent attempts to acquire it from any process or thread will block until it is released; any process or thread may release it. The concepts and behaviors of threading.Lock as it applies to threads are replicated here in multiprocessing.Lock as it applies to either processes or threads, except as noted.
Note that Lock is actually a factory function which returns an instance of multiprocessing.synchronize.Lock initialized with a default context.
Lock supports the context manager protocol and thus may be used in with statements.
acquire ( block = True , timeout = None ) ¶
Acquire a lock, blocking or non-blocking.
With the block argument set to True (the default), the method call will block until the lock is in an unlocked state, then set it to locked and return True . Note that the name of this first argument differs from that in threading.Lock.acquire() .
With the block argument set to False , the method call does not block. If the lock is currently in a locked state, return False ; otherwise set the lock to a locked state and return True .
When invoked with a positive, floating-point value for timeout, block for at most the number of seconds specified by timeout as long as the lock can not be acquired. Invocations with a negative value for timeout are equivalent to a timeout of zero. Invocations with a timeout value of None (the default) set the timeout period to infinite. Note that the treatment of negative or None values for timeout differs from the implemented behavior in threading.Lock.acquire() . The timeout argument has no practical implications if the block argument is set to False and is thus ignored. Returns True if the lock has been acquired or False if the timeout period has elapsed.
Release a lock. This can be called from any process or thread, not only the process or thread which originally acquired the lock.
Behavior is the same as in threading.Lock.release() except that when invoked on an unlocked lock, a ValueError is raised.
class multiprocessing. RLock ¶
A recursive lock object: a close analog of threading.RLock . A recursive lock must be released by the process or thread that acquired it. Once a process or thread has acquired a recursive lock, the same process or thread may acquire it again without blocking; that process or thread must release it once for each time it has been acquired.
Note that RLock is actually a factory function which returns an instance of multiprocessing.synchronize.RLock initialized with a default context.
RLock supports the context manager protocol and thus may be used in with statements.
acquire ( block = True , timeout = None ) ¶
Acquire a lock, blocking or non-blocking.
When invoked with the block argument set to True , block until the lock is in an unlocked state (not owned by any process or thread) unless the lock is already owned by the current process or thread. The current process or thread then takes ownership of the lock (if it does not already have ownership) and the recursion level inside the lock increments by one, resulting in a return value of True . Note that there are several differences in this first argument’s behavior compared to the implementation of threading.RLock.acquire() , starting with the name of the argument itself.
When invoked with the block argument set to False , do not block. If the lock has already been acquired (and thus is owned) by another process or thread, the current process or thread does not take ownership and the recursion level within the lock is not changed, resulting in a return value of False . If the lock is in an unlocked state, the current process or thread takes ownership and the recursion level is incremented, resulting in a return value of True .
Use and behaviors of the timeout argument are the same as in Lock.acquire() . Note that some of these behaviors of timeout differ from the implemented behaviors in threading.RLock.acquire() .
Release a lock, decrementing the recursion level. If after the decrement the recursion level is zero, reset the lock to unlocked (not owned by any process or thread) and if any other processes or threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling process or thread.
Only call this method when the calling process or thread owns the lock. An AssertionError is raised if this method is called by a process or thread other than the owner or if the lock is in an unlocked (unowned) state. Note that the type of exception raised in this situation differs from the implemented behavior in threading.RLock.release() .
class multiprocessing. Semaphore ( [ value ] ) ¶
A semaphore object: a close analog of threading.Semaphore .
A solitary difference from its close analog exists: its acquire method’s first argument is named block, as is consistent with Lock.acquire() .
On macOS, sem_timedwait is unsupported, so calling acquire() with a timeout will emulate that function’s behavior using a sleeping loop.
If the SIGINT signal generated by Ctrl — C arrives while the main thread is blocked by a call to BoundedSemaphore.acquire() , Lock.acquire() , RLock.acquire() , Semaphore.acquire() , Condition.acquire() or Condition.wait() then the call will be immediately interrupted and KeyboardInterrupt will be raised.
This differs from the behaviour of threading where SIGINT will be ignored while the equivalent blocking calls are in progress.
Some of this package’s functionality requires a functioning shared semaphore implementation on the host operating system. Without one, the multiprocessing.synchronize module will be disabled, and attempts to import it will result in an ImportError . See bpo-3770 for additional information.
Shared ctypes Objects¶
It is possible to create shared objects using shared memory which can be inherited by child processes.
multiprocessing. Value ( typecode_or_type , * args , lock = True ) ¶
Return a ctypes object allocated from shared memory. By default the return value is actually a synchronized wrapper for the object. The object itself can be accessed via the value attribute of a Value .
typecode_or_type determines the type of the returned object: it is either a ctypes type or a one character typecode of the kind used by the array module. *args is passed on to the constructor for the type.
If lock is True (the default) then a new recursive lock object is created to synchronize access to the value. If lock is a Lock or RLock object then that will be used to synchronize access to the value. If lock is False then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”.
Operations like += which involve a read and write are not atomic. So if, for instance, you want to atomically increment a shared value it is insufficient to just do
Assuming the associated lock is recursive (which it is by default) you can instead do
Note that lock is a keyword-only argument.
multiprocessing. Array ( typecode_or_type , size_or_initializer , * , lock = True ) ¶
Return a ctypes array allocated from shared memory. By default the return value is actually a synchronized wrapper for the array.
typecode_or_type determines the type of the elements of the returned array: it is either a ctypes type or a one character typecode of the kind used by the array module. If size_or_initializer is an integer, then it determines the length of the array, and the array will be initially zeroed. Otherwise, size_or_initializer is a sequence which is used to initialize the array and whose length determines the length of the array.
If lock is True (the default) then a new lock object is created to synchronize access to the value. If lock is a Lock or RLock object then that will be used to synchronize access to the value. If lock is False then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”.
Note that lock is a keyword only argument.
Note that an array of ctypes.c_char has value and raw attributes which allow one to use it to store and retrieve strings.
The multiprocessing.sharedctypes module¶
The multiprocessing.sharedctypes module provides functions for allocating ctypes objects from shared memory which can be inherited by child processes.
Although it is possible to store a pointer in shared memory remember that this will refer to a location in the address space of a specific process. However, the pointer is quite likely to be invalid in the context of a second process and trying to dereference the pointer from the second process may cause a crash.
Return a ctypes array allocated from shared memory.
typecode_or_type determines the type of the elements of the returned array: it is either a ctypes type or a one character typecode of the kind used by the array module. If size_or_initializer is an integer then it determines the length of the array, and the array will be initially zeroed. Otherwise size_or_initializer is a sequence which is used to initialize the array and whose length determines the length of the array.
Note that setting and getting an element is potentially non-atomic – use Array() instead to make sure that access is automatically synchronized using a lock.
multiprocessing.sharedctypes. RawValue ( typecode_or_type , * args ) ¶
Return a ctypes object allocated from shared memory.
typecode_or_type determines the type of the returned object: it is either a ctypes type or a one character typecode of the kind used by the array module. *args is passed on to the constructor for the type.
Note that setting and getting the value is potentially non-atomic – use Value() instead to make sure that access is automatically synchronized using a lock.
Note that an array of ctypes.c_char has value and raw attributes which allow one to use it to store and retrieve strings – see documentation for ctypes .
multiprocessing.sharedctypes. Array ( typecode_or_type , size_or_initializer , * , lock = True ) ¶
The same as RawArray() except that depending on the value of lock a process-safe synchronization wrapper may be returned instead of a raw ctypes array.
If lock is True (the default) then a new lock object is created to synchronize access to the value. If lock is a Lock or RLock object then that will be used to synchronize access to the value. If lock is False then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”.
Note that lock is a keyword-only argument.
multiprocessing.sharedctypes. Value ( typecode_or_type , * args , lock = True ) ¶
The same as RawValue() except that depending on the value of lock a process-safe synchronization wrapper may be returned instead of a raw ctypes object.
If lock is True (the default) then a new lock object is created to synchronize access to the value. If lock is a Lock or RLock object then that will be used to synchronize access to the value. If lock is False then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”.
Note that lock is a keyword-only argument.
multiprocessing.sharedctypes. copy ( obj ) ¶
Return a ctypes object allocated from shared memory which is a copy of the ctypes object obj.
multiprocessing.sharedctypes. synchronized ( obj [ , lock ] ) ¶
Return a process-safe wrapper object for a ctypes object which uses lock to synchronize access. If lock is None (the default) then a multiprocessing.RLock object is created automatically.
A synchronized wrapper will have two methods in addition to those of the object it wraps: get_obj() returns the wrapped object and get_lock() returns the lock object used for synchronization.
Note that accessing the ctypes object through the wrapper can be a lot slower than accessing the raw ctypes object.
Changed in version 3.5: Synchronized objects support the context manager protocol.
Python Multiprocessing For Beginners
This article is going to teach you, How to apply python multiprocessing for your long-running functions
![]()
What is multiprocessing,
Basically, multiprocessing means run two or more tasks parallely. So in python, We can use python’s inbuilt multiprocessing module to achive that. Imagine you have ten functions that takes ten seconds to run and your at a situation that you want to run that long running function ten times. Without a doubt, It will take hundred seconds to finish if you run it sequentially. That is where multiprocessing comes into action. By using multiprocessing, you can seperate those ten processes into ten sub-processes and complete all in ten seconds.
Different between multiprocessing and multithreading,
So didn’t you wonder why we use multiprocessing instead of multithreading? It is good to use multithreading in the above example, but if your function required more processing power and more memory, It is ideal to use multiprocessing because when you use multiprocessing, each sub-process will have a dedicated CPU and Memory slot. So it is ideal to use multiprocessing instead of multithreading if your long-running function required more processing power and memory.
Let’s see multiprocessing in action,
Imagine this is your long-running function,
The above function will sleep for ten seconds and return. So it mimics the long-running operation.
If you want to run this function ten times without using multiprocessing or multithreading it will look something like this,
What I have done is, I called long_running_function inside a for-loop. For-loop will run ten times and this process will take up to a hundred seconds to complete. Let’s see how to apply multiprocessing to this simple example.
First of all, you will have to import python’s multiprocessing module,
Then you have to make an object from the Process and pass the target function and arguments if any.
As you can see, now we have an object called _process. Which is a multiprocessing process object. So now we can call its start method to start the execution of the long_running_function.
Then our for loop will look like this,
After you calling _process.start(), python will start to execute our function. To wait until all the sub-process complete we have to call the join() methods of our multiprocessing process objects. For that, we have to keep track of all multiprocessing process objects which is created by for loop. To do that, we have to append all _process objects to list called _processes just like below,
After doing that, we can loop through all objects in the _processes list and call the join() method of all process objects like below,
So that is pretty much it. It will run all ten long_running_function calls in ten seconds. The final code will look like below,
This is an old method of doing python multiprocessing but this is solid. In the next articles, I will teach you the latest way of python multiprocessing and also how to get the function’s return data from a multiprocessing process. So stay tuned. Contact me if you have any doubts. Thank you.