micropython / micropython/micropython

Scoped allocation

Open
#4,081 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
C
Stars
22.1k
Forks
9k
Avg merge
6d 4h
Merged PRs (30d)
16

Description

@dpgeorge's comment is from here:

I'm thinking: @micropython.temp serves as a context which results in a C-call to switch a malloc function

Yes, I think this is a pretty decent idea. I had a similar idea for a while which is "scoped allocation", whereby all allocations within a function call are allocated in a new "heap scope", and then the entire scope is freed upon exit of the function. Eg:

@micropython.heap_on_stack(200)
def foo(x, y):
l = [x, y]
return len(l)
The idea here is that the function foo() is wrapped in a new heap and the semantics of calling foo are:

200 bytes are allocated on the C stack and used to create a temporary "heap"
allocation on this heap is simply a matter of incrementing a pointer and checking that it didn't go beyond the extents (of 200 bytes in this case); there is no GC'ing of this temporary heap
all malloc/free functions in the runtime are switched to use this temporary heap for the duration of the foo execution
the function foo runs, allocates a new list, computes its length, and returns this integer
as foo returns the temporary heap is destroyed, along with all objects created on it (in this case the list l)
the result of foo is a small int and doesn't need the heap and is returned to the caller
The execution of foo is highly deterministic, in terms of memory use and execution time. Using scoped allocation allows you to allocate in a hard interrupt. The downside of this approach is that foo must not leak any scope-allocated objects into the outer scope, because these objects won't exist once foo returns. Note also that you can nest the allocation scopes.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or entry points are named. Start by tracing MicroPython's runtime allocation paths and the decorator behavior described in the issue; define the scope semantics, nesting and object-lifetime constraints before implementation, with tests covering allocation and cleanup.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
embedded-iot
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.