簡體   English   中英

在多線程環境中交換c ++映射對象

[英]swap c++ map objects in multithreaded environment

我是C ++編碼的新手,有必要用新構建的multimap對象交換/替換舊的multimap對象,因為此對象將被緩存,我想僅在構建新對象並替換該對象之后才替換現有對象本身。 這將在多線程環境中使用,因此使用原子負載。 如該線程中所述, 希望有一種有效的方法來交換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();
}

輸出:

第一個字符串
第一個字符串
第二串
第二串
第二串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM