Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <atomic>
#include <memory>
#include <vector>
#include <thread>
#include <cstdio>
std::shared_ptr<std::vector<int>> v;
void read(const char* name) {
auto localv = std::atomic_load_explicit(&v, std::memory_order_acquire);
long sum = 0;
for (int x : *localv) sum += x;
printf("read(%s) sum = %ld\n", name, sum);
}
void replace() {
std::atomic_store_explicit(&v, std::make_shared<std::vector<int>>(100, 2), std::memory_order_release);
}
int main() {
v.reset(new std::vector<int>(10000000, 1));
std::thread t1(read, "t1");
std::thread t2(read, "t2");
std::thread t3(replace);
t3.join();
std::thread t4(read, "t4");
std::thread t5(read, "t5");
t1.join();t2.join();t4.join();t5.join();
}
// $ g++ -std=c++11 -pthread atomic_replace_vector.cc
// $ valgrind --leak-check=yes ./a.out
// ==2006== Memcheck, a memory error detector
// ==2006== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
// ==2006== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
// ==2006== Command: ./a.out
// ==2006==
// read(t2) sum = 200
// read(t4) sum = 200
// read(t5) sum = 200
// read(t1) sum = 10000000
// ==2006==
// ==2006== HEAP SUMMARY:
// ==2006== in use at exit: 72,704 bytes in 1 blocks
// ==2006== total heap usage: 17 allocs, 16 frees, 40,075,648 bytes allocated
// ==2006==
// ==2006== LEAK SUMMARY:
// ==2006== definitely lost: 0 bytes in 0 blocks
// ==2006== indirectly lost: 0 bytes in 0 blocks
// ==2006== possibly lost: 0 bytes in 0 blocks
// ==2006== still reachable: 72,704 bytes in 1 blocks
// ==2006== suppressed: 0 bytes in 0 blocks
// ==2006== Reachable blocks (those to which a pointer was found) are not shown.
// ==2006== To see them, rerun with: --leak-check=full --show-leak-kinds=all
// ==2006==
// ==2006== For counts of detected and suppressed errors, rerun with: -v
// ==2006== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment