0
Peer* Subtracker::getPeer(int packetNum, Peer* p, Peer* nearestP)
{
    lock_guard<mutex> guard(this->m);
    double d = DBL_MAX;
    for(auto it:packetToPeersMapping[packetNum])
    {
        double dTemp = sqrt(pow(p->x - it->x, 2) + pow(p->y - (it)->y, 2));
        if(dTemp <= d)
        {
            nearestP = it;
        }
    }
    packetToPeersMapping[packetNum].push_back(p);

    return nearestP;    
}
void Peer::operate()
{
    // some initial code    

    for(int i=0;i<NUM_PACKETS;i++)
    {
        if(packets.find(i)!=packets.end())
        {
            // Packet already with peer do nothing
            packetTime[i] = {this->ID, 0};
        }
        else
        {
            Peer *peer = nullptr;
            peer = subtracker->getPeer(i, this, peer);

            packets.insert(i);
            packetTime[i] = {peer->ID, expression to calculate time};

        }
    }

    // SOME OTHER CODE
}

I am using lock_guard for synchronization among peers accessing the subtrackers. There are some peers and one of those peers is also a subtracker. The job of subtracker getPeer() method is to calculate the nearest peer which contains a certain packet which the requesting peer needs. Synchronization is basically needed in packetToPeersMapping, which contains the info about the peers having a particular packet. Each peer is a separate thread and has a subtracker assigned to it.

Ideally, if a peer needs a packet, it will call the getPeer() method and the nearest peer will be returned. Upon running the code, sometimes even if the current peer does not have the necessary packet, the getPeer() method is returning the current peer as the nearest peer having the packet. I think there is something wrong with the way I'm using lock_guard

Priyanshu
  • 21
  • 1
  • 6
  • 1
    Unfortunately, because the shown code does not meet the requirements for a [mre], it is unlikely that anyone will be able to tell you anything. – Sam Varshavchik Apr 05 '21 at 10:44
  • What happens if two `Peer` instances call `subtracker->getPeer(i, this, peer);` with same value of `i` (if that's possible)? Can they return the same `Peer *`? If so, you possibly have a race condition. Really need to see more code though -- preferably a [mcve]. – G.M. Apr 05 '21 at 11:02

0 Answers0