What does it mean to lock or unlock a JsVar?

Posted on
  • I'm learning to create my own extensions for Espruino. I have read the various guides and documentation and referred to existing libraries which have enabled me to succeed in making a simple extension that does not leak memory.

    My success is despite uncertainty around the purpose of jsUnLock() and when to use it. My understanding so far is:

    1. A locked JsVar will not be collected by the GC
    2. All jsvNew[Whatever]() functions return locked variables.
    3. Any JsVar that is not intentionally returned to user code should be
      unlocked.
    4. Any JsVar that is returned (or child there of) should remain locked.

    Have I misunderstood anything? Is there anything significant I am missing?

  • Hi! That sounds spot on.

    The reasoning behind the lock counter is that sometimes (GC, as you mentioned, or when compacting variables) the interpreter needs to know when a variable is 'in use' and so cannot be moved around or freed.

    The vars have a 'lock counter' which you can read either using the trace() JS command or with jsvGetLocks() from C. Basically if the variable is just sitting there not being used by any C code, it should have no locks at all.

    If you have a pointer to the variable in your C code, the variable should be locked.

    If you compile without RELEASE=1 some assertions get built in, and those check for the lock count getting too high or decremented too much - so it's a good way to sanity check what you're doing (even if you have to temporarily pull out some features in order to get the build to fit in flash)

    Hope that helps!

  • Hi Gordon, thank you for taking the time to provide a very helpful answer. I feel more confident about what I'm doing now.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

What does it mean to lock or unlock a JsVar?

Posted by Avatar for Gary.Ott @Gary.Ott

Actions