samedi 10 avril 2021

C++ program with shared data between two functions

I have a program very similar to the one below where it is trying to use some shared data between two asynchronous functions.

#include <mutex>

class myclass {
public:
   myclass() {numPackets = 0;}
   ~myclass() = default;
   void funcA(PacketA_t &pktA);
   void funcB(PacketB_t &pktB);

private:
   unsigned int numPackets;
   PacketB_t packetB;
   std::mutex pktMutex;
};

void myclass::funcB(PacketB_t &pktB)
{
   pktMutex.lock();
   packetB = pktB;
   ++numPackets;
   pktMutex.unlock();
}

void myclass::funcA(PacketA_t &pktA)
{
   pktMutex.lock();
   /*
   code for comparing pktA with packetB
   */
   --numPackets;
   pktMutex.unlock();
}

funcA and funcB are both callback functions which receive slightly different versions (PacketA_t and PacketB_t) of the same information from different stages of the pipeline. My goal is to compare each packet received by the two functions and see if the information within is actually the same or not.

We cannot assume anything about the exact order of calling between funcA and funcB, but we can assume they are in lockstep (that is, for each packet received by funcA, funcB will also receive that packet before receiving any other packet).

However, when I run the program, it hangs. Any suggestion on what I am doing wrong would be appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire