swap c++ map objects in multithreaded environment

落爺英雄遲暮 提交于 2019-12-11 16:57:30

问题


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

But I'm getting this error

error: expected expression
refresh= {swap.m2,swap.m1};

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


回答1:


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

Output:

first string
first string
second string
second string
second string



来源:https://stackoverflow.com/questions/56086143/swap-c-map-objects-in-multithreaded-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!