我有一个方法:
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
}
当包括睡眠和锁时,我得到:
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 143
Killed - processing time exceeded
不过,如果我注释所有锁和this_thread::sleep_for
,它会按照预期工作。我需要锁,因为我正在处理其他线程。完整的代码如下所示:https://godbolt.org/z/7erjrg,因为otput提供的信息不多,所以我很累
您还没有发布NEXT_STEP
的代码和MTX
的定义,这是重要的信息。
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];
}
如果您阅读了std::mutex的手册,您会发现:
和std::unique_lock:
从move_robot
调用的next_step
违反了这一点,它试图锁定调用线程已经拥有的互斥对象。
您的问题的相关主题是unique_lock是否可以与recursive_mutex一起使用?。这样你就得到了解决办法:
std::recursive_mutex mtx;
std::unique_lock<std::recursive_mutex> lck(mtx);