Search code examples
c++multithreadingmultimap

swap c++ map objects in multithreaded environment


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?


Solution

  • 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