1

I have a method:

void move_robot(const vector<vector<double> > &map) {
    // accumulate the footprint while the robot moves
    // Iterate through the path
        //std::unique_lock<std::mutex> lck(mtx);
        for (unsigned int i=1; i < map.size(); i++) {

            while (distance(position , map[i]) > DISTANCE_TOLERANCE ) {
                this->direction = unitary_vector(map[i], this->position);
                this->next_step();
                lck.unlock();
                this_thread::sleep_for(chrono::milliseconds(10)); // sleep for 500 ms
                lck.lock();
            }
            std::cout << "New position is x:" << this->position[0] << " and y:" << this->position[1] << std::endl;
        }
        this->moving = false;
        // notify to end
    }

When the sleep and locks are included I get:

ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 143

Killed - processing time exceeded 

Nevertheless, if I comment all the locks and this_thread::sleep_for it works as expected. I need the locks because I am dealing with other threads. The complete code is this one: https://godbolt.org/z/7ErjrG I am quite stacked because the otput does not provide much information

Hector Esteban
  • 1,011
  • 1
  • 14
  • 29

1 Answers1

1

You have not posted the code of next_step and the definition of mtx, this is important information.

std::mutex mtx;

void next_step() {
  std::unique_lock<std::mutex> lck(mtx);
  this->position[0] += DT * this->direction[0];
  this->position[1] += DT * this->direction[1];
}

If you read the manual for std::mutex you find out:

  • A calling thread must not own the mutex prior to calling lock or try_lock.

And std::unique_lock:

  1. Locks the associated mutex by calling m.lock(). The behavior is undefined if the current thread already owns the mutex except when the mutex is recursive.

next_step called from move_robot violates this, it tries to lock already owned mutex object by that calling thread.

The relative topic for your question is Can unique_lock be used with a recursive_mutex?. There you get the fix:

std::recursive_mutex mtx;
std::unique_lock<std::recursive_mutex> lck(mtx);
273K
  • 29,503
  • 10
  • 41
  • 64