High-performance and seamless sharing and modification of Python objects between processes, without the periodic overhead of serialization and deserialization. Provides fast inter-process communication (IPC) via shared memory. Supports NumPy, Torch arrays, custom classes (including dataclass), classes with methods, and asyncio
!!! Updated to the multiprocessing (processes > 2) version from Cengal v5.0.0. Documentation and examples will be added later. The old version is available via the following import path: from ipcpyobjects.versions.v_1 import *
InterProcessPyObjects package
InterProcessPyObjects is a part of the Cengal library. If you have any questions or would like to participate in discussions, feel free to join the Cengal Discord. Your support and involvement are greatly appreciated as Cengal evolves.
This high-performance package delivers blazing-fast inter-process communication through shared memory, enabling Python objects to be shared across processes with exceptional efficiency. By minimizing the need for frequent serialization-deserialization, it enhances overall speed and responsiveness. The package offers a comprehensive suite of functionalities designed to support a diverse array of Python types and facilitate asynchronous IPC, optimizing performance for demanding applications.


API State
Stable. Guaranteed to not have braking changes in the future (see bellow for details).
Any hypothetical further API-breaking changes will lead to new module creation within the package. An old version will continue its existence and continue to be importable by an explicit address (see Details bellow).
Details
The current (currently latest) version can be imported either by:
from ipcpyobjects import *
or by
from ipcpyobjects.versions.v_1 import *
If further braking changes will be made to the API - a new (v_2) version will be made. As result:
Current (v_1) version will continue to be accessible by an explicit address:
from ipcpyobjects.versions.v_1 import *
Latest (v_2) version will be accessible by either:
from ipcpyobjects import *
or by
from ipcpyobjects.versions.v_2 import *
This is a general approach across the entire Cengal library. It gives me the ability to effectively work on its huge codebase, even by myself.
By the way. I'm finishing an implementation of CengalPolyBuild - my package creation system which provides same approach to users. It is a comprehensive and hackable build system for multilingual Python packages: Cython (including automatic conversion from Python to Cython), C/C++, Objective-C, Go, and Nim, with ongoing expansions to include additional languages. Basically, it will provide easy access to all the same features I'm already using in the Cengal library package creation and management processes.
Key Features
- Shared Memory Communication:
- Lock-Free Synchronization:
- Supported Python Types:
None, bool, 64-bit int, large int (arbitrary precision integers), float, complex, bytes, bytearray, str.
* Standard types: Decimal, slice, datetime, timedelta, timezone, date, time
* Containers: tuple, list, classes inherited from: AbstractSet (frozenset), MutableSet (set), Mapping and MutableMapping (dict).
* Pickable classes instances: custom classes including dataclass
* Allows mutable containers (lists, sets, mappings) to save basic types (None, bool, 64 bit int, float) internally, optimizing memory use and speed.
- NumPy and Torch Support:
- Custom Class Support:
dataclasses) onto shared dictionaries in shared memory.
* Modifies the class instance to override attribute access methods, managing data fields within the shared dictionary.
* supports classes with or without dict attr
* supports classes with or without slots attr
- Asyncio Compatibility:
Import
To use this package, simply install it via pip:
pip install InterProcessPyObjects
Then import it into your project:
from ipcpyobjects import *
Main principles
- only one process has access to the shared memory at the same time
- working cycle:
- do not forget to manually destroy your shared objects when they are not needed already
- feel free to not destroy your shared object if you need it for a whole run and/or do not care about the shared memory waste
- data will not be preserved between Creator's sessions. Shared memory will be wiped just before Creator finished its work with a shared memory instance (Consumer's session will be finished already at this point)
! Important about hashmaps
Package, currently, uses Python hash() call which is reliable across interpreter session but unreliable across different interpreter sessions because of random seeding.
In order to use same seeding across different interpreter instances (and as result, be able to use hashmaps) you can set 'PYTHONHASHSEED env var to some fixed integer value
<details> <summary title=".bashrc"><kbd> .bashrc </kbd></summary>
<pre><code class="lang-bash">export PYTHONHASHSEED=0</code></pre>
</details>
<details> <summary title="Your bash script"><kbd> Your bash script </kbd></summary>
<pre><code class="lang-bash">export PYTHONHASHSEED=0 python YOURSCRIPT.py</code></pre>
</details>
<details> <summary title="Terminal"><kbd> Terminal </kbd></summary>
<pre><code class="lang-shell">$ PYTHONHASHSEED=0 python YOURSCRIPT.py</code></pre>
</details>
An issue with the behavior of an integrated hash() call does Not affect the following data types: None, bool, int, float, complex, str, bytes, bytearray Decimal, slice, datetime, timedelta, timezone, date, time tuple, list set wrapped by FastLimitedSet class instance: for example by using .putmessage(FastLimitedSet(myset_obj)) call dict wrapped by FastLimitedDict class instance: for example by using .putmessage(FastLimitedDict(mydict_obj)) call dataclass by default: for example by using .putmessage(myobj) call dataclass wrapped by ForceStaticObjectCopy or ForceStaticObjectInplace class instances. For example by using .putmessage(ForceStaticObjectInplace(myobj)) call It affects only the following data types: AbstractSet (frozenset) MutableSet (set) Mapping MutableMapping (dict) dataclass wrapped by ForceGeneralObjectCopy or ForceGeneralObjectInplace class instances. For example by using .putmessage(ForceGeneralObjectInplace(myobj)) call Examples
- An async examples (with asyncio):
Receiver.py performance measurements
- CPU: i5-3570@3.40GHz (Ivy Bridge)
- RAM: 32 GBytes, DDR3, dual channel, 655 MHz
- OS: Ubuntu 20.04.6 LTS under WSL2. Windows 10
# We create local variables once in order to access them many times in the future, ensuring high performance. # Applying a principle that is widely recommended for improving Python code. companymetrics: List = sso.companyinfo.companymetrics # 12479 iterations/seconds someemployee: Employee = sso.companyinfo.someemployee # 10568 iterations/seconds datadict: Dict = sso.datadict # 16_362 iterations/seconds numpyndarray: np.ndarray = datadict['key3'] # 26_223 iterations/seconds
Optimal work with shared data (through local variables):
async with asharedmemorycontextmanager as sharedmemory: # List k = companymetrics[CompanyMetrics.avgsalary] # 1535267 iterations/seconds k = companymetrics[CompanyMetrics.employees] # 1498_278 iterations/seconds k = companymetrics[CompanyMetrics.inagoodstate] # 1154454 iterations/seconds k = companymetrics[CompanyMetrics.websites] # 380258 iterations/seconds companymetrics[CompanyMetrics.annualincome] = 2000000.0 # 1380983 iterations/seconds companymetrics[CompanyMetrics.employees] = 20 # 1352_799 iterations/seconds companymetrics[CompanyMetrics.avgsalary] = 5000.0 # 1300_966 iterations/seconds companymetrics[CompanyMetrics.inagoodstate] = None # 1224573 iterations/seconds companymetrics[CompanyMetrics.inagoodstate] = False # 1213175 iterations/seconds companymetrics[CompanyMetrics.avgsalary] += 1.1 # 299_415 iterations/seconds companymetrics[CompanyMetrics.employees] += 1 # 247476 iterations/seconds companymetrics[CompanyMetrics.emails] = tuple() # 55335 iterations/seconds (memory allocation performance is planned to be improved) companymetrics[CompanyMetrics.emails] = ('sails@company.com',) # 30314 iterations/seconds (memory allocation performance is planned to be improved) companymetrics[CompanyMetrics.emails] = ('sails@company.com', 'support@company.com') # 20860 iterations/seconds (memory allocation performance is planned to be improved) companymetrics[CompanyMetrics.websites] = ['http://company.com', 'http://company.org'] # 10465 iterations/seconds (memory allocation performance is planned to be improved) # Method call on a shared object that changes a property through the method someemployee.increaseyearsofemployment() # 80548 iterations/seconds# Object properties k = sso.intvalue # 850098 iterations/seconds k = sso.strvalue # 228966 iterations/seconds sso.intvalue = 200 # 207480 iterations/seconds sso.intvalue += 1 # 152263 iterations/seconds sso.strvalue = 'Hello. ' # 52390 iterations/seconds (memory allocation performance is planned to be improved) sso.strvalue += '!' # 35823 iterations/seconds (memory allocation performance is planned to be improved)
# Numpy.ndarray numpyndarray += 10 # 403646 iterations/seconds numpyndarray -= 15 # 402107 iterations/seconds
# Dict k = datadict['key1'] # 87558 iterations/seconds k = datadict[('key', 2)] # 49338 iterations/seconds datadict['key1'] = 200 # 86744 iterations/seconds datadict['key1'] += 3 # 41409 iterations/seconds datadict['key1'] *= 1 # 40927 iterations/seconds datadict[('key', 2)] = 'value2' # 31460 iterations/seconds (memory allocation performance is planned to be improved) datadict[('key', 2)] = datadict[('key', 2)] + 'd' # 18_972 iterations/seconds (memory allocation performance is planned to be improved) datadict[('key', 2)] = 'value2' # 10941 iterations/seconds (memory allocation performance is planned to be improved) datadict[('key', 2)] += 'd' # 16568 iterations/seconds (memory allocation performance is planned to be improved)
An example of non-optimal work with shared data (without using a local variables):
async with asharedmemorycontextmanager as sharedmemory: # An example of a non-optimal method call (without using a local variable) that changes a property through the method sso.companyinfo.someemployee.increaseyearsofemployment() # 9418 iterations/seconds# An example of non-optimal work with object properties (without using local variables) k = sso.companyinfo.income # 20445 iterations/seconds sso.companyinfo.income = 3000000.0 # 13899 iterations/seconds sso.companyinfo.income *= 1.1 # 17272 iterations/seconds sso.companyinfo.income += 500000.0 # 18_376 iterations/seconds # Example of non-optimal usage of numpy.ndarray without a proper local variable datadict['key3'] += 10 # 6319 iterations/seconds
Notify the sender about the completion of work on the shared object
async with asharedmemorycontextmanager as sharedmemory: sso.someprocessingstagecontrol = True # 298968 iterations/seconds</code></pre>Reference (and explaining examples line by line)
Code for shared memory Creator side: <pre><code class="lang-python">asharedmemorymanager: ASharedMemoryManager = ASharedMemoryManager(SharedMemory('sharedmemoryidentifier', create=True, size=200 1024*2))
declare creation and initiation of the shared memory instance with a size of 200 MiB.</code></pre>
Code for shared memory Consumer side: <pre><code class="lang-python">asharedmemorymanager: ASharedMemoryManager = ASharedMemoryManager(SharedMemory('sharedmemoryidentifier'))
declares connection to shared memory instance</code></pre>
On shared memory Creator side: <pre><code class="lang-python">async with asharedmemorymanager as asmm:
creates, initiates shared memory instance and waits for the Consumer creation. Execute it once per run.
feel free to share either asmm or asharedmemorymanager across your coroutines</code></pre>
On shared memory concumer side: <pre><code class="lang-python">async with asharedmemorymanager as asmm:
waits for the shared memory creation and initiation by the shared memory Creator. Execute it once per run.
feel free to share either asmm or asharedmemorymanager across your coroutines</code></pre>
<pre><code class="lang-python">asharedmemorycontext_manager: ASharedMemoryContextManager = asmm()
creates shared memory access context manager. Create it once per coroutine. Use in the same coroutine as much as you need it.</code></pre>
<pre><code class="lang-python">async with asharedmemorycontextmanager as sharedmemory:
acquire access to shared memory as soon as possible</code></pre>
<pre><code class="lang-python">async with asharedmemorycontextmanager.ifhasmessages() as sharedmemory:
acquire access to shared memory if message queue is not empty</code></pre>
<pre><code class="lang-python">shared_memory # is an instance of ValueHolder class from the Cengal library shared_memory.value # is an instance of SharedMemory instance shared_memory.existence # bool. Will be set to True at the beginning of an each context (with) block. Set it to False # if you want to release CPU for a small time portion before shared memory will be acquired next time. # if at least one coroutine will not set it to False - next acquire attempt will be made immediately which will # lower latency and increase performance but at the same time will consume more CPU time. # Default behavior (True) is better for CPU intensive algorithms, # while False on all process coroutines (which have their own memory access context managers) will be better # for example for desktop or mobile applications</code></pre>
SharedMemory fields and methods you might frequently use in an async approach (in coroutines)
<pre><code class="lang-python">SharedMemory.size # an actual size of the shared memory</code></pre>
<pre><code class="lang-python">SharedMemory.name # an identifier of the shared memory</code></pre>
<pre><code class="lang-python">SharedMemory.create # True on Creator side. False on Consumer side</code></pre>
<pre><code class="lang-python">objmapped = sharedmemory.value.put_message(obj)
Puts object to the shared memory and create an appropriate message
Returns mapped version of the object if applicable (returns the same object otherwise).
Next types will return same object: None, bool, int, float, str, bytes, bytearray, tuple.</code></pre>
<pre><code class="lang-python">objmapped, sharedobjoffset = sharedmemory.value.putmessage2(obj)
Puts object to the shared memory and create an appropriate message
Returns:
* Mapped version of the object if applicable (returns the same object otherwise).
Next types will return same object: None, bool, int, float, str, bytes, bytearray, tuple.
* An offset to the shared object data structure which holds an appropriate shared object content</code></pre>
<pre><code class="lang-python">hasmessages: bool = sharedmemory.value.has_messages()
main way for checking an internal message queue for an emptiness</code></pre>
<pre><code class="lang-python">objmapped = sharedmemory.value.take_message()
Takes (and removes) the latest message from an internal message queue.
Creates and returns mapped object from an appropriate shared object data structure.
Does not deletes an appropriate shared object data structure.
Returns mapped version of the object if applicable (returns new copy of an object otherwise).
Next types will return new copy of an object: None, bool, int, float, str, bytes, bytearray, tuple.
Will raise NoMessagesInQueueError exception if an internal message queue is empty</code></pre>
<pre><code class="lang-python">objmapped, sharedobjoffset = sharedmemory.value.takemessage2()
Takes (and removes) the latest message from an internal message queue.
Creates and returns mapped object from an appropriate shared object data structure.
Does not deletes an appropriate shared object data structure.
Returns:
* Mapped version of the object if applicable (returns new copy of an object otherwise).
Next types will return new copy of an object: None, bool, int, float, str, bytes, bytearray, tuple.
* An offset to the shared object data structure which holds an appropriate shared object content
Will raise NoMessagesInQueueError exception if an internal message queue is empty</code></pre>
<pre><code class="lang-python">sharedmemory.value.destroyobj(sharedobjoffset)
Destroys the shared object data structure which holds an appropriate shared object content.
Use it in order to free memory used by your shared object.
sharedmemory.value.destroyobject(sharedobjoffset)
An alias to the sharedmemory.value.destroyobj() call</code></pre>
<pre><code class="lang-python">sharedobjbuffer: memoryview = sharedmemory.value.getobjbuffer(sharedobj_offset)
returns memoryview to the data section of your shared object.
Feel free to use this memory for your own needs while an appropriate shared object is still not destroyed.
Next types provides buffer to their shared data: bytes, bytearray, str, numpy.ndarray (buffer of an appropriate shared bytes object mapped by this ndarray), torch.Tensor (buffer of an appropriate shared bytes object mapped by this Tensor)</code></pre>
Useful exceptions
<pre><code class="lang-python">class SharedMemoryError:
Base exception all other exceptions are inherited from it</code></pre>
<pre><code class="lang-python">class FreeMemoryChunkNotFoundError(SharedMemoryError): """Indicates that an unpartitioned chunk of free memory of requested size not being found.
Regarding this error, itβs important to adjust the size parameter in the SharedMemory configuration. Trying to estimate memory consumption down to the byte is not practical because it fails to account for the memory overhead required by each entity stored (such as entity type metadata, pointers to child entities, etc.).
When setting the size parameter for SharedMemory, consider using broader units like tens (for embedded systems), hundreds, or thousands of megabytes, rather than precise byte counts. This approach is similar to how you would not precisely calculate the amount of memory needed for a web server hosted externally; you make an educated guess, like assuming that 256 MB might be insufficient but 768 MB could be adequate, and then adjust based on practical testing.
Also, be aware of memory fragmentation, which affects all memory allocation systems, including the OS itself. For example, if you have a SharedMemory pool sized to store exactly ten 64-bit integers, accounting for additional bytes for system information, your total might be around 200 bytes. Initially, after storing the integers, your memory might appear as ["int", "int", ..., "int"]. If you delete every second integer, the largest contiguous free memory chunk could be just 10 bytes, despite having 50 bytes free in total. This fragmentation means you cannot store a larger data structure like a 20-byte string which needs contiguous space.
To resolve this, simply increase the size parameter value of SharedMemory. This is akin to how you would manage memory allocation for server hosting or thread stack sizes in software development. """</code></pre>
<pre><code class="lang-python">NoMessagesInQueueError
Next calls can raise it if an internal message queue is empty: takemessage(), takemessage2(), readmessage(), readmessage2()</code></pre>
Performance tips
<details> <summary title="Data structures"><kbd> Data structures </kbd></summary>
Data structures
It is recommended to use IntEnum+list based data structures instead of dictionaries or even instead custom class instancess (including dataclass) if you want best performance.
For example instead operating with dict:
<details> <summary title="Example"><kbd> Example </kbd></summary>
Message sender
<pre><code class="lang-python">company_metrics: Dict[str, Any] = { 'websites': ['http://company.com', 'http://company.org'], 'avgsalary': 3000.0, 'employees': 10, 'inagood_state': True, } companymetricsmapped: List = sharedmemory.value.putmessage(company_metrics)</code></pre>
Message receiver
<pre><code class="lang-python">companymetrics: Dict[str, Any] = sharedmemory.value.take_message() k = companymetrics['employees'] # 87558 iterations/seconds companymetrics['employees'] = 200 # 86744 iterations/seconds companymetrics['employees'] += 3 # 41409 iterations/seconds</code></pre>
</details> <br>
or even instead operating with dataclass (classes by default operate faster then dict):
<details> <summary title="Example"><kbd> Example </kbd></summary>
Message sender
<pre><code class="lang-python">@dataclass class CompanyMetrics: income: float employees: int avg_salary: float annual_income: float inagood_state: bool emails: Tuple websites = List[str]
company_metrics: CompanyMetrics = CompanyMetrics( income=1.4, employees: 12, avg_salary: 35.0, annualincome: 30000.0, inagood_state: False, emails: ('sails@company.com', 'support@company.com'), websites = ['http://company.com', 'http://company.org'], ) companymetricsmapped: CompanyMetrics = sharedmemory.value.putmessage(company_metrics)</code></pre>
Message receiver
<pre><code class="lang-python">companymetrics: CompanyMetrics = sharedmemory.value.take_message() k = companymetrics.employees # 850098 iterations/seconds companymetrics.employees = 200 # 207480 iterations/seconds companymetrics.employees += 1 # 152263 iterations/seconds</code></pre>
</details> <br>
it would be more beneficial to operate with a list and appropriate IntEnum indexes:
<details> <summary title="Example"><kbd> Example </kbd></summary>
Message sender:
<pre><code class="lang-python">class CompanyMetrics(IntEnum): income = 0 employees = 1 avg_salary = 2 annual_income = 3 inagood_state = 4 emails = 5 websites = 6
companymetrics: List = intenumdicttolist({ # lists with IntEnum indexes are blazing-fast alternative to dictionaries CompanyMetrics.websites: ['http://company.com', 'http://company.org'], CompanyMetrics.avgsalary: 3000.0, CompanyMetrics.employees: 10, CompanyMetrics.inagood_state: True, }) # Unmentioned fields will be filled with Null values companymetricsmapped: List = sharedmemory.value.putmessage(company_metrics)</code></pre>
Message receiver:
<pre><code class="lang-python">companymetrics: List = sharedmemory.value.take_message() k = companymetrics[CompanyMetrics.avgsalary] # 1535267 iterations/seconds companymetrics[CompanyMetrics.avgsalary] = 5000.0 # 1300_966 iterations/seconds companymetrics[CompanyMetrics.avgsalary] += 1.1 # 299_415 iterations/seconds</code></pre>
</details> <br>
</details>
<details> <summary title="Sets"><kbd> Sets </kbd></summary>
Sets
You might use FastLimitedSet wrapper for your set in order to get much faster shared sets.
Just wrap your dictionary with FastLimitedSet:
<pre><code class="lang-python">my_obj: List = [ True, 2, FastLimitedSet({ 'Hello ', 'World', 3, }) ] myobjmapped = sharedmemory.value.putmessage(my_obj)</code></pre>
Drawbacks of this approach: only initial set of items will be shared. Changes made to the mapped objects (an added or deleted items) will not be shared and will not be visible by other process.
</details>
<details> <summary title="Dictionaries"><kbd> Dictionaries </kbd></summary>
Dictionaries
You might use FastLimitedDict wrapper for your dict in order to get much faster shared dictionary.
Just wrap your dictionary with FastLimitedDict:
<pre><code class="lang-python">my_obj: List = [ True, 2, FastLimitedDict({ 1: 'Hello ', '2': 'World', 3: np.array([1, 2, 3], dtype=np.int32), }) ] myobjmapped = sharedmemory.value.putmessage(my_obj)</code></pre>
Drawbacks of this approach: only initial set of key-values pairs will be shared. Added, updated or deleted key-value pairs will not be shared and such changes will not be visible by other process.
</details>
<details> <summary title="Custom classes (including dataclass)"><kbd> Custom classes (including dataclass) </kbd></summary>
Custom classes (including dataclass)
By default, shared custom class instances (including dataclass instances) have static set of attributes (similar to instances of classes with slots). That means that all new (dynamically added to the mapped object, attributes will not became shared). This behavior increases performance.
<details> <summary title="For example"><kbd> For example </kbd></summary>
For example
<pre><code class="lang-python">@dataclass class SomeSharedObject: someprocessingstage_control: bool int_value: int str_value: str data_dict: Dict[Hashable, Any] company_info: CompanyInfo
my_obj: List = [ True, 2, SomeSharedObject( someprocessingstage_control=False, int_value=18, str_value='Hello, ', data_dict=None, company_info=None, ), ] myobjmapped: List = sharedmemory.value.putmessage(my_obj)
myobjmapped[2].somenewattribute = 'Hi!' # this attribute will Not became shared and as result will not became accessible by other process</code></pre>
</details>
If you need to share class instance with ability to add new shared attributes to it's mapped instance, you can wrap your object with either ForceGeneralObjectCopy or ForceGeneralObjectInplace
<details> <summary title="For example"><kbd> For example </kbd></summary>
For example
<pre><code class="lang-python">@dataclass class SomeSharedObject: someprocessingstage_control: bool int_value: int str_value: str data_dict: Dict[Hashable, Any] company_info: CompanyInfo
my_obj: List = [ True, 2, ForceGeneralObjectInplace(SomeSharedObject( someprocessingstage_control=False, int_value=18, str_value='Hello, ', data_dict=None, company_info=None, )), ] myobjmapped: List = sharedmemory.value.putmessage(my_obj)
myobjmapped[2].somenewattribute = 'Hi!' # this attribute Will became shared and as result Will be seen by process</code></pre>
</details>
Difference between ForceGeneralObjectCopy and ForceGeneralObjectInplace: ForceGeneralObjectInplace. myobjmapped = sharedmemory.value.putmessage(ForceGeneralObjectInplace(myobj)) call will change class of an original myobj object. And True == (myobj is myobj_mapped) ForceGeneralObjectCopy. myobjmapped = sharedmemory.value.putmessage(ForceGeneralObjectCopy(myobj)) call will Not change an original myobj object. myobjmapped object will be constructed from the scratch Also you can tune a default behavior by wrapping your object with either ForceStaticObjectCopy or ForceStaticObjectInplace.
Difference between ForceStaticObjectCopy and ForceGeneralObjectInplace: ForceGeneralObjectInplace. myobjmapped = sharedmemory.value.putmessage(ForceGeneralObjectInplace(myobj)) call will change class of an original myobj object. And True == (myobj is myobj_mapped) ForceStaticObjectCopy. myobjmapped = sharedmemory.value.putmessage(ForceStaticObjectCopy(myobj)) call will Not change an original myobj object. myobjmapped object will be constructed from the scratch </details>
How to choose shared memory size
<details> <summary title="How to choose shared memory size"><kbd> How to choose shared memory size </kbd></summary>
When setting the size parameter for SharedMemory, consider using broader units like tens (for embedded systems), hundreds, or thousands of megabytes, rather than precise byte counts. This approach is similar to how you would not precisely calculate the amount of memory needed for a web server hosted externally; you make an educated guess, like assuming that 256 MB might be insufficient but 768 MB could be adequate, and then adjust based on practical testing.
Also, be aware of memory fragmentation, which affects all memory allocation systems, including the OS itself. For example, if you have a SharedMemory pool sized to store exactly ten 64-bit integers, accounting for additional bytes for system information, your total might be around 200 bytes. Initially, after storing the integers, your memory might appear as ["int", "int", ..., "int"]. If you delete every second integer, the largest contiguous free memory chunk could be just 10 bytes, despite having 50 bytes free in total. This fragmentation means you cannot store a larger data structure like a 20-byte string which needs contiguous space.
To resolve this, simply increase the size parameter value of SharedMemory. This is akin to how you would manage memory allocation for server hosting or thread stack sizes in software development.
</details>
Benchmarks
<details> <summary title="System"><kbd> System </kbd></summary>
- CPU: i5-3570@3.40GHz (Ivy Bridge)
- RAM: 32 GBytes, DDR3, dual channel, 655 MHz
- OS: Ubuntu 20.04.6 LTS under WSL2. Windows 10
Throughput GiB/s

<details> <summary title="Benchmarks results"><kbd> Benchmarks results </kbd></summary>
Refference results (sysbench)
<pre><code class="lang-bash">sysbench memory --memory-oper=write run</code></pre>
<pre><code class="lang-">5499.28 MiB/sec</code></pre>
Results

multiprocessing.shared_memory.py - simple implementation. This is a simple implementation because it uses a similar approach to the one used in uvloop., asyncio.*, multiprocessing.Queue, and multiprocessing.Pipe benchmarking scripts. Similar implementations are expected to be used by the majority of projects.
Benchmarks results table
| Approach | sync/async | Throughput GiB/s | |---------------------------------|------------|------------------| | InterProcessPyObjects (sync) | sync | 3.770 | | InterProcessPyObjects + uvloop | async | 3.222 | | InterProcessPyObjects + asyncio | async | 3.079 | | multiprocessing.shared_memory | sync | 2.685 | | uvloop.UnixDomainSockets | async | 0.966 | | asyncio + cengal.Streams | async | 0.942 | | uvloop.Streams | async | 0.922 | | asyncio.Streams | async | 0.784 | | asyncio.UnixDomainSockets | async | 0.708 | | multiprocessing.Queue | sync | 0.669 | | multiprocessing.Pipe | sync | 0.469 |
Benchmark scripts
- InterProcessPyObjects - Sync:
- InterProcessPyObjects - Async (uvloop):
- InterProcessPyObjects - Async (asyncio):
- multiprocessing.shared_memory.py
- uvloop.UnixDomainSockets.py
- asynciowith_cengal.Streams.py
- uvloop.Streams.py
- asyncio.Streams.py
- asyncio.UnixDomainSockets.py
- multiprocessing.Queue.py
- multiprocessing.Pipe.py
Shared Dict Performance

<details> <summary title="Benchmarks results"><kbd> Benchmarks results </kbd></summary>
Competitors:
1. multiprocessing.Manager - dict
Pros:
- Part of the standard library
- Slowest solution
- Values are read-only unless they are an explicit instances of multiprocessing.Manager
supported types (types inherited frommultiprocessing.BaseProxylikemultiprocessing.DictProxyormultiprocessing.ListProxy)
2. UltraDict
Pros:
- Relatively fast writes
- Fast repetitive reads of an unchanged values
- Has built in inter-process synchronization mechanism
- Relies on pickle on an each change
- Non-dictionary values are read-only from the multiprocessing perspective
3. sharedmemory_dict
Pros:
- At least faster than 'multiprocessing.Manager - dict' solution
- Second slowest solution
- Relies on pickle on an each change
- Values (even lists or dicts) are read-only from the multiprocessing perspective
- Can not be initialized from the other dict
nor even from the otherSharedMemoryDictinstance: you need to manually put an each key-value pair into it using loop - Has known issues with inter-process synchronization. Is is better for developer to use their own external inter-process synchronization mechanisms (from multiprocessing.Manager
for example)
4. InterProcessPyObjects - IntEnumListStruct
Pros:
- Fastest solution: 15.6 times faster than UltraDict
- Good for structures: when all fields are already known
- Support any InterProcessPyObjects' supported data types as values
- Values of mutable types are naturally mutable: developer do not need to prepare and change their data explicitly
- Can use only IntEnum (int) keys
- Fixed size of a size of a provided IntEnum
<pre><code class="lang-python">class CompanyMetrics(IntEnum): income = 0 employees = 1 avg_salary = 2 annual_income = 3 inagood_state = 4 emails = 5 websites = 6
companymetrics: List = intenumdicttolist({ # lists with IntEnum indexes are blazing-fast alternative to dictionaries CompanyMetrics.websites: ['http://company.com', 'http://company.org'], CompanyMetrics.avgsalary: 3000.0, CompanyMetrics.employees: 10, CompanyMetrics.inagood_state: True, }) # Unmentioned fields will be filled with Null values companymetricsmapped: List = sharedmemory.value.putmessage(company_metrics)</code></pre>
Message receiver example:
<pre><code class="lang-python">companymetrics: List = sharedmemory.value.take_message() k = companymetrics[CompanyMetrics.avgsalary] companymetrics[CompanyMetrics.avgsalary] = 5_000.0 companymetrics[CompanyMetrics.avgsalary] += 1.1</code></pre>
5. InterProcessPyObjects - Dataclass
Pros:
- Fast. Second fastest solution: around 2 times faster than UltraDict
- Good for structures and object: when all fields are already known
- Works with objects naturally - without an explicit preparation or changes from the developer's side
- Support any InterProcessPyObjects' supported data types as values
- Supports dataclass
as well as other objects - Supports object's methods
- Fields of mutable types are naturally mutable: developer do not need to prepare and change their data explicitly
- Does not relies on frequent data pickle: uses pickle only for an initial object construction but not for the fields updates
- Set of fields is fixed by the set of fields of an original object
6. InterProcessPyObjects - Dict
Pros:
- Slightly faster than SharedMemoryDict
- Works with objects naturally - without an explicit preparation or changes from the developer's side
- Support any InterProcessPyObjects' supported data types as values
- Support any InterProcessPyObjects' supported Hashable data types as keys
- Values of mutable types are naturally mutable: developer do not need to prepare and change their data explicitly
- Does not relies on pickle
- Speed optimizations are architectures and planned for an implementation
- Speed optimization implementation are in progress - not released yet
Results

Benchmarks results table
| Approach | increments/s | |-------------------------------------------|--------------| | InterProcessPyObjects - IntEnumListStruct | 1189730 | | InterProcessPyObjects - Dataclass | 143091 | | UltraDict | 76214 | | InterProcessPyObjects - Dict | 44285 | | SharedMemoryDict | 42862 | | multiprocessing.Manager - dict | 2751 |
</details>
Todo
- [ ] Connect more than two processes
- [ ] Use third-party fast hashing implementations instead of or in addition to built in hash()` call
- [ ] Continuous performance improvements
Conclusion
This Python package provides a robust solution for inter-process communication, supporting a variety of Python data structures, types, and third-party libraries. Its lock-free synchronization and asyncio compatibility make it an ideal choice for high-performance, concurrent execution.
Based on Cengal
This is a stand-alone package for a specific Cengal module. Package is designed to offer users the ability to install specific Cengal functionality without the burden of the library's full set of dependencies.
The core of this approach lies in our 'cengal-light' package, which houses both Python and compiled Cengal modules. The 'cengal' package itself serves as a lightweight shell, devoid of its own modules, but dependent on 'cengal-light[full]' for a complete Cengal library installation with all required dependencies.
An equivalent import:
from cengal.hardware.memory.shared_memory import * from cengal.parallelexecution.asyncio.asharedmemory_manager import *
Cengal library can be installed by:
pip install cengal
https://github.com/FI-Mihej/Cengal
https://pypi.org/project/cengal/
Projects using Cengal
- CengalPolyBuild - A Comprehensive and Hackable Build System for Multilingual Python Packages: Cython (including automatic conversion from Python to Cython), C/C++, Objective-C, Go, and Nim, with ongoing expansions to include additional languages. (Planned to be released soon)
- cengalappdirpath_finder - A Python module offering a unified API for easy retrieval of OS-specific application directories, enhancing data management across Windows, Linux, and macOS
- cengalcpu_info - Extended, cached CPU info with consistent output format.
- cengalmemory_barriers - Fast cross-platform memory barriers for Python.
- fletasync - wrapper which makes Flet async and brings booth Cengal.coroutines and asyncio to Flet (Flutter based UI)
- justpycontainers - wrapper around JustPy in order to bring more security and more production-needed features to JustPy (VueJS based UI)
- Bensbach - decompiler from Unreal Engine 3 bytecode to a Lisp-like script and compiler back to Unreal Engine 3 bytecode. Made for a game modding purposes
- Realistic-Damage-Model-mod-for-Long-War - Mod for both the original XCOM:EW and the mod Long War. Was made with a Bensbach, which was made with Cengal
- SmartCATaloguer.com - TagDB based catalog of images (tags), music albums (genre tags) and apps (categories)
License
Copyright Β© 2012-2026 ButenkoMS. All rights reserved.
Licensed under the Apache License, Version 2.0.