Question about locks and callbacks

Posted on
  • Is the following code safe?

      JsVar *params[2];
      params[0] = jsvNewNull();
      params[1] = jsAccessPointArray;
      jsiQueueEvents(NULL, g_jsScanCallback, params, 2);
    
      jsvUnLock(jsAccessPointArray);
      jsvUnLock(g_jsScanCallback);
      jsvUnLock(params[0]);
      g_jsScanCallback = NULL;
      return;
    

    The reason I'm wondering is that this schedules a callback and then immediately proceeds to release locks (is there really a lock on the null object?). Is this safe because the callback is guaranteed to be completed before the next GC run? (Is GC not run automatically if an allocation fails?)

    NB: this snippet came from https://github.com/espruino/Espruino/blo­b/master/libs/network/esp8266/jswrap_esp­8266_network.c#L2008-L2016

  • Yes, that looks fine to me. It's safe because jsiQueueEvents will add references to all the stuff it cares about, so even when unlocked it won't get freed.

    In that case I'd consider using jsvUnLock3 though - it's stupid, but I changed all the multiple unlocks to calls to jsvUnLock2 and jsvUnLock3, and saved about 10kB of flash IIRC :)

    Also there's jsvUnLockMany that you can use on arrays of JsVars

  • Just to add, whether it is safe depends on jsAccessPointArray. If that hasn't been created or locked previously then you could end up unlocking too many times, which would probably cause an assert fail.

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

Question about locks and callbacks

Posted by Avatar for tve @tve

Actions