samedi 2 avril 2022

Segmentation fault with std::promise::set_value( ) depending on order of function calls

can you please help me make sense of the behavior outlined below? The short summary is that the call to std::promise::set_value() results in a segmentation fault if the callback function (invoked from a different thread) is updated prior to the call to "set_value()" whereas, everything works smoothly if the callback function is updated AFTER the call to "set_value()".

Please let me know if any additional information is needed in this regard.

void ExecuteSetupProcecure(unsigned int NodeId) {
  this->barrier = std::promise<void>();
  std::future<void> barrier_future = barrier.get_future();

  pServer->RegisterCallbackForSetup([this, NodeId] (uint64_t newNodeId) { ***<-- Called from a different thread upon completion of 'setup'.***
          if (NodeId == newNodeId) {
              /* pServer->RegisterCallbackForSetup(nullptr) */  ***<-- If this line is activated, the next line results in a segmentation fault.***
              barrier.set_value();
              pServer->RegisterCallbackForSetup(nullptr); ***<-- No segmentation fault in the previous line if this line is activated.***
          }
      });
  barrier_future.wait();

void Server::RegisterCallbackForSetup(std::function<void(uint64_t)> CallBackForSetup) {
    this->CallBackForSetup = CallBackForSetup;
}

Note: I understand that there could be some thread-safety issues with the implementation of RegisterCallbackForSetup( ) as defined above if we have lots of readers and writers. However, right now, I have exactly one thread that sets this value and one thread that reads/ uses this value.

best regards, pvenk

Aucun commentaire:

Enregistrer un commentaire