I am facing the following problem. I have a protected data structure a map
of <ID , Object>
. There is only one map data structure and multiple threads might want to set
and get
values from the map using an ID
. The Object
could be nested as shown in the following sample code.
#include <iostream>
#include <map>
#include <algorithm>
#include <mutex>
using namespace std;
struct C {
int r;
char s;
};
struct B {
int p;
char q;
C c;
};
struct A {
int x;
int y;
B b;
char z;
};
/*
A
L__ x
|
L__ y
|
L__ B
L__p
|
L__q
|
L__C
L__r
|
L__s
*/
/* the follwing is the
data structure to store objects of of type A
corresponding to an ID (int)
*/
map<int,A> Map;
mutex m;
/* Follwing are the desired
api's to set and get values from the Map
Locks are also required to handle concurrency
*/
void getValueFromMap(int id,/* what to pass ?? */) {
m.lock();
/* code to get the value of the specified varible */
m.unlock();
}
void setValueInMap(int id,/* what to pass ?? */) {
m.lock();
/* code to set the new value to the specified variable */
m.unlock();
}
int main() {
/* lets suppose Map has some A type objects already */
int id = 4;
/* assume I want to change the information (value of p) of id = 4*/
/* instead of doing the following */
m.lock();
Map[id].b.p = 12; /*update to some value */
m.unlock();
/* what I need the follwing */
setValueInMap(4,/* what_to_change , what_is_the_new_value etc .. */);
/*similarly */
/*if I want get the value of s */
int s;
m.lock();
getValueFromMap(id,/* what_to_get,placeholder (for example &s) */);
m.unlock();
}
I want to have some api
calls ( for example setValueInMap
with fixed number of arguments ) to set
and get
values of the map
using function calls and all the mutex work will happen inside those api
calls only. Although I have shown only one generic set function to set all types of member variables of struct A
, it need not be (more api function calls is of no problem).
How it can be implemented?
thanks!
Aucun commentaire:
Enregistrer un commentaire