Question

Not sure if I worded the title correctly, but bear with me and all will be explained...

We have a collection of code not invented here which uses inter-process comms (IPC messaging). The very rough outline of the scheme is something like this:

comms.c contains:

static int our_id;

void init_messaging(int id)
{
   our_id = id;
   Msg_Init(KEY);
}

void get_some_data_from_elsewhere(target_id)
{
   send_message(target_id, our_id); // Send to target, return to us
   rcv_message(<our_id>); // get messages addressed to <our_id>
}

Then stuff.c might do:

init_messaging(ID_STUFF);
get_some_data(target);

And foo.c might ALSO do:

init_messaging(ID_FOO);
get_some_data(target);

How this works / should work / the Elbonian Code Slaves seemingly expected it to work:

When stuff.c calls init_messaging, our_id is set to ID_STUFF and any further calls from that process will have the variable "ID_STUFF" available to ensure replies on the message queue come back to the correct process.

HOWEVER, if we have this situation, of two or more threads spawned from the same place, it all falls down:

stuff.c might do:

void stuff_thread()
{
    init_messaging(ID_STUFF);
    get_some_data(target);
}

void things_thread()
{
    init_messaging(ID_THINGS);
    get_some_data(target);
}

If this happens, when stuff_thread starts, our_id is set to ID_STUFF, but then when things_thread starts, our_id is over-written to ID_THINGS, so things_thread can end up getting data meant for stuff_thread.

Now, this is clearly a rather shaky, but I'm not sure what the proper / least worst way of doing this is without having to pass an extra variable to every call to get_some_data() etc.

It seems what we need is something as mentioned in the "seldom_correct.h" example here: https://stackoverflow.com/a/1433387/1389218 Where every inclusion of comms.h would spawn a new copy of our_id - except that we want multiple copies for each time we call init_messaging();

Or perhaps to make our_id an extern something like this: comms.h

extern int our_id;

stuff.c might do:

#include "comms.h"

void stuff_thread()
{
    our_id = ID_STUFF;
    init_messaging(our_id);
    get_some_data(target);
}

Having a search round SO hasn't yet yielded any elegant-looking answers.

Was it helpful?

Solution

Hat tip to ChrisJ.Kiick, declaring:

static __thread int our_id;

Did the trick!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top