在多线程环境中交换C 地图对象
swap c++ map objects in multithreaded environment
我是C 编码的新手,需要交换/替换旧构建的Multimap对象,将其替换为CACHE,我想替换现有对象仅在构建新对象并替换对象本身之后。这将用于多线程环境中,因此使用原子负载。如该线程中所述,需要一种有效的方法来交换C 中的两个指针。我写了这个代码
#include<iostream>
#include<map>
#include<atomic>
#include<string>
using namespace std;
// MultiMap Object
struct mmap{
multimap<string,int> stringTointmap;
};
// Structure to swap two instances of multimap
struct swapMap{
mmap* m1;
mmap* m2;
};
int main(){
//create Two Objects
mmap* old = new mmap();
mmap* new2= new mmap();
// populate first object
old->stringTointmap.insert(make_pair("old",1));
//populate second object
new2->stringTointmap.insert(make_pair("new1",2));
//swap two objects
atomic<swapMap> swap;
auto refresh=swap.load();
refresh= {swap.m2,swap.m1};
}
但是我遇到了这个错误
error: expected expression
refresh= {swap.m2,swap.m1};
当然,我缺少某些东西,有人可以帮忙吗?
以下是示例代码,显示了如何在 std::shared_ptr
上使用原子操作。
#include <memory>
#include <thread>
#include <chrono>
#include <atomic>
#include <iostream>
std::shared_ptr<std::string> the_string;
int main()
{
std::atomic_store(&the_string, std::make_shared<std::string>("first string"));
std::thread thread(
[&](){
for (int i = 0; i < 5; ++i)
{
{
// pin the current instance in memory so we can access it
std::shared_ptr<std::string> s = std::atomic_load(&the_string);
// access it
std::cout << *s << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
std::this_thread::sleep_for(std::chrono::seconds(2));
// replace the current instance with a new instance allowing the old instance
// to be removed when all threads are done with it
std::atomic_store (&the_string, std::make_shared<std::string>("second string"));
thread.join();
}
输出:
第一个字符串
第一个字符串
第二个字符串
第二个字符串
第二个字符串
相关文章:
- 如何从地图中删除矢量对象
- 跨多个对象使用地图
- 如何制作带有对象的多重地图? - C++
- 将对象放入地图后打印对象
- 如何在C++中将可调用对象放入地图中?
- C++ 在地图上循环 - 消失的对象
- 为什么地图需要实现'operator<'以及如何比较对象?
- 在地图上启动对象的正确方式
- 按unique_pointer将传递的对象存储在地图中
- 为什么我不能在 c++ 中将对象插入到地图中
- 如何调用返回双精度或字符串并将其保存在地图上但作为对象的类的方法
- 在多线程环境中交换C 地图对象
- 在C 地图中使用对象作为密钥和值
- 从地图访问对象会导致新对象C 的实例化
- 无法访问/存储地图中的游戏状态对象
- 在C++中向地图添加对对象的引用
- 使用什么数据结构来存储基于游戏对象的二维单元地图?
- 如何创建结构类型数组的地图对象
- 比较地图对象及其引用C++
- 如何打印地图对象