Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing messages between threads and memory management

I'm writing a C++ application with two threads. Thread A will send messages to thread B. The message type could be:

struct MyMessageType
{
  int a;
  enum MyEnum b;
  bool someFlag;
}

A std::queue<MyMessageType> messageQueue is shared between the threads for passing messages.

In the sending thread, I'll have something like:

struct MyMessageType newMessage;
newMessage.a = 14;
newMessage.b = someEnumeratedValue;
newMessage.someFlag = false;
GrabTheMutexProtectingTheQueue();
messageQueue.push(newMessage);
ReleaseTheMutexProtectingTheQueue();

My question is regarding memory management, and is twofold:

A) How do I ensure that the pointer to newMessage is valid when the receiving thread gets the message? What would happen, for instance, if the function that created newMessage ended and newMessage therefore went out of scope before the receiving thread processed the message?

B) Once I can ensure that the newMessage pointer is valid when the receiving thread processes it, how to I free up the memory that was used by the struct?

like image 240
The Demigeek Avatar asked Apr 17 '13 01:04

The Demigeek


1 Answers

The std::queue push() function stores a copy of whatever you give it (see here), so you don't have to worry about it going out of scope.

The copy in the queue will survive until you delete it with pop().

So, on the sending side, it's a simple matter of (for example):

lock_mutex();
myqueue.push (something);
unlock_mutex();
// Do whatever you want with something, the queue has a copy

and, at the receiving end:

lock_mutex();
while (myqueue.empty()) {
    unlock_mutex();
    // possibly yield to another thread
    lock_mutex();
}
something = myqueue.front();
weaveMagicWith (something);
myqueue.pop();
unlock_mutex();

Of course, you can re-engineer that to minimise the duration of the mutex lock on the receiving end (if, for example, weaving magic takes a long time), it's just a rough example showing one way to do it.

like image 88
paxdiablo Avatar answered Sep 29 '22 12:09

paxdiablo