在多线程环境中交换c ++映射对象 [英] swap c++ map objects in multithreaded environment

查看:82
本文介绍了在多线程环境中交换c ++映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++编码的新手,需要用新构建的Multimap对象交换/替换旧的Multimap对象,因为该对象将被缓存,我想仅在构建新对象之后才替换现有对象,并且替换对象本身.这将在多线程环境中使用,因此使用原子负载.如该线程中所述,想要高效在C ++中交换两个指针的方法.我写了这段代码

I am new to c++ coding and have a need to swap/replace the old multimap object with the newly built multimap object, as this object will be cache I would like to replace the existing object only after building the new object and just replace the object itself. This will be used in a multithreaded environment, so using the atomic load. As described in this thread Want an efficient way to swap two pointers in C++. I wrote this code

#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};

肯定是我缺少了什么,有人可以帮忙吗?

definitely, I'm missing something, could someone please help?

推荐答案

下面的示例代码显示了如何在std::shared_ptr上使用原子操作来实现它.

Here's example code showing how to use atomic operations on a std::shared_ptr to do it.

#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();
}

输出:

第一个字符串
第一个字符串
第二个字符串
第二个字符串
第二个字符串

first string
first string
second string
second string
second string

这篇关于在多线程环境中交换c ++映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆