problem while accessing same object from multiple threads simultaneously using lock_guard

63 views Asked by At
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

0

There are 0 answers