Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a deadlock #431

Merged
merged 1 commit into from
May 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 34 additions & 9 deletions subt_ign/src/BaseStationPlugin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -89,22 +89,47 @@ void BaseStationPlugin::OnArtifact(const std::string &_srcAddress,
//////////////////////////////////////////////////
void BaseStationPlugin::RunLoop()
{
std::map<std::string, std::vector<subt::msgs::ArtifactScore>> scoresCopy;
while (this->running)
{
// Send the scores, and clear the score list.
// Copy the scores so that we don't lock the mutex when calling
// this->client->SendTo(data, scorePair.first) because we could end in a
// deadlock.
//
// Process 1:
// 1. BaseStationPlugin::RunLoop() locks this->mutex.
// 2. Call this->client->SendTo(data, scorePair.first) which goes
// to Broker::OnMessage(const subt::msgs::Datagram &_req))
// 4. Attmepts to lock Broker's mutex but the mutex is held by
// Process 2.
//
// Process 2:
// 1. Broker::DispatchMessages(): Locks the Broker's mutex. Which
// blocks Process 1.
// 2. An artifact report goes to BaseStationPlugin::OnArtifact.
// 3. Attemps to lock BaseStationPlugin's mutex. However, this
// mutex is lock by Process 1.
{
std::scoped_lock<std::mutex> lk(this->mutex);
for (const std::pair<std::string, std::vector<subt::msgs::ArtifactScore>>
&scorePair : this->scores)
scoresCopy = this->scores;
}

// Send the scores, and clear the score list.
for (const std::pair<std::string, std::vector<subt::msgs::ArtifactScore>>
&scorePair : scoresCopy)
{
for (const subt::msgs::ArtifactScore &score : scorePair.second)
{
for (const subt::msgs::ArtifactScore &score : scorePair.second)
{
std::string data;
score.SerializeToString(&data);
this->client->SendTo(data, scorePair.first);
}
std::string data;
score.SerializeToString(&data);
this->client->SendTo(data, scorePair.first);
}
}

{
std::scoped_lock<std::mutex> lk(this->mutex);
this->scores.clear();
scoresCopy.clear();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
Expand Down