Skip to content

Commit

Permalink
fix: add mutex protection for robot_date to ensure thread safety in m…
Browse files Browse the repository at this point in the history
…ulti-threaded environments
  • Loading branch information
fan-ziqi committed Oct 16, 2024
1 parent 6e09eb9 commit 26166fb
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/rl_sar/library/rl_sdk/rl_sdk.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <iostream>
#include <string>
#include <unistd.h>
#include <mutex>

#include <yaml-cpp/yaml.h>

Expand Down Expand Up @@ -123,6 +124,7 @@ class RL

RobotState<double> robot_state;
RobotCommand<double> robot_command;
std::mutex robot_state_mutex;

// init
void InitObservations();
Expand Down
4 changes: 4 additions & 0 deletions src/rl_sar/src/rl_real_a1.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ void RL_Real::SetCommand(const RobotCommand<double> *command)

void RL_Real::RobotControl()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

this->motiontime++;

this->GetState(&this->robot_state);
Expand All @@ -148,6 +150,8 @@ void RL_Real::RobotControl()

void RL_Real::RunModel()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

if (this->running_state == STATE_RL_RUNNING)
{
this->obs.ang_vel = torch::tensor(this->robot_state.imu.gyroscope).unsqueeze(0);
Expand Down
4 changes: 4 additions & 0 deletions src/rl_sar/src/rl_real_go2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ void RL_Real::SetCommand(const RobotCommand<double> *command)

void RL_Real::RobotControl()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

this->motiontime++;

this->GetState(&this->robot_state);
Expand All @@ -153,6 +155,8 @@ void RL_Real::RobotControl()

void RL_Real::RunModel()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

if (this->running_state == STATE_RL_RUNNING)
{
this->obs.ang_vel = torch::tensor(this->robot_state.imu.gyroscope).unsqueeze(0);
Expand Down
4 changes: 4 additions & 0 deletions src/rl_sar/src/rl_sim.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ void RL_Sim::SetCommand(const RobotCommand<double> *command)

void RL_Sim::RobotControl()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

if (this->control.control_state == STATE_RESET_SIMULATION)
{
gazebo_msgs::SetModelState set_model_state;
Expand Down Expand Up @@ -216,6 +218,8 @@ void RL_Sim::JointStatesCallback(const sensor_msgs::JointState::ConstPtr &msg)

void RL_Sim::RunModel()
{
std::lock_guard<std::mutex> lock(robot_state_mutex);

if (this->running_state == STATE_RL_RUNNING && simulation_running)
{
this->obs.lin_vel = torch::tensor({{this->vel.linear.x, this->vel.linear.y, this->vel.linear.z}});
Expand Down

0 comments on commit 26166fb

Please sign in to comment.