我需要分享一张地图:
map <string, vector< pair <string,string> > > repoMap;
父进程和分叉子进程中的使每个进程都知道 其中一个在地图中添加/删除一个元素。
请提供一个小而快速的解决方案。
答案 0 :(得分:0)
“保持跟踪”在低语言编程中并不真实。您可以执行以下操作:
我将提供一个快速的解决方案,但是你必须学到更多才能让它变得更加漂亮。
C ++ 11中的关键是使用std::mutex
,它在地图上提供锁定。例如:
std::mutex lock; //must be accessible by all threads, either being global (not the best, but will work) or put it in your class body
void addElementToMap(map<string, vector< pair <string,string> > >& myMap, string key, pair element)
{
std::lock_guard<std::mutex> guard(lock);
myMap[key] = element;
//the guard will be unlocked when destroyed
}
现在您可以使用std::thread
来调用此函数,例如:
std::thread myThread(addElementToMap, std::ref(mapToModify), key, element);
您在此处使用std::ref()
,因为通常会将副本提供给线程。
好像你必须学习C ++ 11的所有新功能。 This是一本好书。
随意提问,但也请对此进行一些研究。
祝你好运!