我面临以下问题.我有一个受保护的数据结构a map中<ID , Object>.只有一个地图数据结构和多个线程可能想要使用的地图set和get值ID.在Object如图所示的以下示例代码可被嵌套.
#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();
}
Run Code Online (Sandbox Code Playgroud)
我希望有一些api调用(例如setValueInMap具有固定数量的参数)set和使用函数调用的get值,map并且所有互斥体工作将api仅在这些调用中发生.虽然我只显示了一个通用的set函数来设置所有类型的成员变量struct A,但它不一定是(更多api函数调用没有问题).
如何实施?
谢谢!
如何使通用函数在地图上起作用:
std::map<int, A> Map;
std::mutex m;
template <typename F>
auto ActOnMap(F&& f) -> decltype(f(Map)) {
std::lock_guard<std::mutex> locker(m);
return f(Map);
}
Run Code Online (Sandbox Code Playgroud)
(注意:你应该创建一个类来构造它并隐藏对mapand的直接访问mutex.)
然后:
/* 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*/
ActOnMap([id](std::map<int, A>&m){ m[id].b.p = 12;});
/*similarly */
/*if I want get the value of s */
int s = ActOnMap([id](std::map<int, A>&m){ return m[id].b.c.s;});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |