-
Notifications
You must be signed in to change notification settings - Fork 169
Memory leaking in the Delay_ms module #138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The problem arises because the code keeps creating new instances of I appreciate that MicroPython should detect that old instances are no longer referenced and GC them. I'm not sure why this isn't happening. However needlessly instantiating objects is poor practice. The following fixes this behaviour: import asyncio
from primitives import Delay_ms
import gc
async def todo_3():
print('todo_3' )
async def todo_2(d):
print('start todo_2')
d.trigger()
print('end todo_2')
async def main():
d = Delay_ms(todo_3, duration=1000) # Instantiate once only
for _ in range(10):
print("\nStart main")
print("mem_free = ", gc.mem_free())
await todo_2(d)
await asyncio.sleep_ms(2000)
gc.collect()
print("END main")
asyncio.run(main()) |
On further thought, a second way to fix this is to call import asyncio
from primitives import Delay_ms
import gc
async def todo_3():
print('todo_3' )
async def todo_2():
d = Delay_ms(todo_3, duration=1000)
print('start todo_2')
d.trigger()
print('end todo_2')
d.deinit()
async def main():
for _ in range(10):
print("\nStart main")
print("mem_free = ", gc.mem_free())
await todo_2()
await asyncio.sleep_ms(2000)
gc.collect()
print("END main")
asyncio.run(main()) While this works, the first suggestion is better for the reasons given. |
Thank you for the quick and complete answer. |
Good day!
Board: stm32f411
OS: Micropython v1.23.0
I have found that when I use the Delay_ms module the board memory always became smaller and smaller even If I collect the garbage regularly. This code shows such behavior:
In result memory starts leaking after three cycles :
In my real program I need to create an async task sometime that have to callback some function with time delay.
Then I tried the different approach and it works well:
Now I think, am I doing everything right with Delay_ms?
The text was updated successfully, but these errors were encountered: