bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.73k stars 1.12k forks source link

Is ArduinoJson thread-safe? #1122

Closed mouridis closed 5 years ago

mouridis commented 5 years ago

Sorry, this is not an issue but a question really.

I'm using ArduinoJson in an ESP32 based project (using ESP32 Arduino core). I have custom functions which accept JSON documents as a String objects and they use ArduinoJson to manipulate them (return a value given a key, add a key/value pair etc).

For example:

String getJSONValue(String JSONMessage, String key) {  // returns String because my JSONs strictly contain String values, so the returned String, depending on the actual JSONMessage is either the value or a string serialised JSON Array that corresponds to given key. 
  DynamicJsonDocument inputDoc(heapAllocatedForEachJSONDocument);  // heapAllocatedForEachJSONDocument is const unsigned int (global)
  DeserializationError inputError = deserializeJson(inputDoc, JSONMessage);
  JsonObject inputObj = inputDoc.as<JsonObject>();
  if (!inputError) {
    String arrayValue;
    serializeJson(inputObj[key], arrayValue);
    if (arrayValue.substring(0, 1).equals("[")) { // this is stupid and probably there's a much better way to detect array value.
      return arrayValue;
    } else {
      return String(inputObj[key] | unavailableString.c_str());
    }
  } else {
    return unavailableString; // unavailableString is global String
  }
}

The thing is, these functions are called from multiple threads in my code and I was wondering if this is safe. I would guess that since the functions create new objects each time they are called and they do not manipulate let's say a global json object, it's safe. Right?

Also, how about in general? Is ArduinoJson thread-safe in general?

bblanchon commented 5 years ago

Hi @mouridis,

Each JsonDocument is independent and there is no global variable in ArduinoJson. ArduinoJson is thread-safe as long as you use a different JsonDocument in each thread.

Best Regards, Benoit

mouridis commented 5 years ago

Thank you!