leggedrobotics / ocs2

Optimal Control for Switched Systems
https://leggedrobotics.github.io/ocs2
BSD 3-Clause "New" or "Revised" License
874 stars 225 forks source link

Multithreading memory safety of CppAdInterface #42

Closed ghost closed 2 years ago

ghost commented 2 years ago

Hi,

Is CppAdInterface thread-safe? I used CppAdInterface for constraint and dynamics calculation but encountered some multithreading memory problems. On memory allocation/de-allocation of Eigen matrix or std::vector throughout the pipeline (from getting constraint Jacobian to the destruction of ocs2::ModelData), the debugger reports memory problem randomly including double free and invalid pointer. However with single threaded SLQ, everything is fine.

I didn't use the provided MPC-ROS interface; instead, I directly call run(...,...) of GaussNewtonDDP_MPC. The official example of anymal runs well on my computer so I think I may have ignored some important steps.

rubengrandia commented 2 years ago

We treat the CppAdInterface as not thread-safe. (It might be so, but one would have to dig into the 3rd party library to verify this). The solver will create 1 clone of the optimal control problem per thread. Each thread has therefore its own copy of each part of the model, and there will be no simultaneous calls to the same CppAdInterface.

One possible problem could be that the clone method in your own constraint is not implemented 100% correctly.

ghost commented 2 years ago

We treat the CppAdInterface as not thread-safe. (It might be so, but one would have to dig into the 3rd party library to verify this). The solver will create 1 clone of the optimal control problem per thread. Each thread has therefore its own copy of each part of the model, and there will be no simultaneous calls to the same CppAdInterface.

One possible problem could be that the clone method in your own constraint is not implemented 100% correctly.

You are right! I thought its not important and did not implement the copy constrcutor. Now everything seems to work well. I will update if there are further problems.