Container System 0.1.0
High-performance C++20 type-safe container framework with SIMD-accelerated serialization
Loading...
Searching...
No Matches
thread_safe_rcu_example.cpp File Reference
#include "container.h"
#include <atomic>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
Include dependency graph for thread_safe_rcu_example.cpp:

Go to the source code of this file.

Functions

int main ()
 

Function Documentation

◆ main()

int main ( )

Definition at line 25 of file thread_safe_rcu_example.cpp.

26{
27 std::cout << "=== Thread-Safe RCU Container Example ===" << std::endl;
28
29 // Shared container with mutex for thread safety
30 value_container shared_container;
31 std::mutex container_mutex;
32
33 shared_container.set("counter", static_cast<int64_t>(0));
34 shared_container.set("status", std::string("initializing"));
35
36 // 1. Concurrent writes
37 std::cout << "\n1. Concurrent writes (5 threads):" << std::endl;
38 std::atomic<int> write_count{0};
39 std::vector<std::thread> writers;
40
41 for (int i = 0; i < 5; ++i)
42 {
43 writers.emplace_back(
44 [&, i]()
45 {
46 for (int j = 0; j < 10; ++j)
47 {
48 std::lock_guard<std::mutex> lock(container_mutex);
49 std::string key = "thread_" + std::to_string(i) + "_item_" + std::to_string(j);
50 shared_container.set(key, std::string("value_" + std::to_string(j)));
51 write_count.fetch_add(1);
52 }
53 });
54 }
55
56 for (auto& t : writers)
57 {
58 t.join();
59 }
60 std::cout << " Total writes: " << write_count.load() << std::endl;
61 std::cout << " Container size: " << shared_container.size() << std::endl;
62
63 // 2. Concurrent reads
64 std::cout << "\n2. Concurrent reads (3 threads):" << std::endl;
65 std::atomic<int> read_count{0};
66 std::vector<std::thread> readers;
67
68 for (int i = 0; i < 3; ++i)
69 {
70 readers.emplace_back(
71 [&, i]()
72 {
73 std::lock_guard<std::mutex> lock(container_mutex);
74 auto size = shared_container.size();
75 read_count.fetch_add(1);
76 std::cout << " Reader " << i << " sees " << size << " entries" << std::endl;
77 });
78 }
79
80 for (auto& t : readers)
81 {
82 t.join();
83 }
84 std::cout << " Total reads: " << read_count.load() << std::endl;
85
86 // 3. Container copy for snapshot
87 std::cout << "\n3. Snapshot (copy-on-read):" << std::endl;
88 std::shared_ptr<value_container> snapshot;
89 {
90 std::lock_guard<std::mutex> lock(container_mutex);
91 snapshot = shared_container.copy(true);
92 }
93 std::cout << " Snapshot size: " << snapshot->size() << std::endl;
94 std::cout << " Original size: " << shared_container.size() << std::endl;
95
96 std::cout << "\nDone." << std::endl;
97 return 0;
98}