c - Creating multiple instances/copies of a static global -


not sure if worded title correctly, bear me , explained...

we have collection of code not invented here uses inter-process comms (ipc messaging). rough outline of scheme 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 target, return    rcv_message(<our_id>); // messages addressed <our_id> } 

then stuff.c might do:

init_messaging(id_stuff); get_some_data(target); 

and foo.c might do:

init_messaging(id_foo); get_some_data(target); 

how works / should work / elbonian code slaves seemingly expected work:

when stuff.c calls init_messaging, our_id set id_stuff , further calls process have variable "id_stuff" available ensure replies on message queue come correct process.

however, if have situation, of 2 or more threads spawned same place, 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 happens, when stuff_thread starts, our_id set id_stuff, when things_thread starts, our_id over-written id_things, things_thread can end getting data meant stuff_thread.

now, rather shaky, i'm not sure proper / least worst way of doing without having pass variable every call get_some_data() etc.

it seems need mentioned in "seldom_correct.h" example here: https://stackoverflow.com/a/1433387/1389218 every inclusion of comms.h spawn new copy of our_id - except want multiple copies each time call init_messaging();

or perhaps make our_id extern 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 search round hasn't yet yielded elegant-looking answers.

hat tip chrisj.kiick, declaring:

static __thread int our_id; 

did trick!


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -