| 105 | } |
| 106 | |
| 107 | void demonstrateThreadSafeFunctor() |
| 108 | { |
| 109 | std::cout << "\n=== Thread-Safe Coordination Demo ===\n"; |
| 110 | |
| 111 | std::atomic<int> callCount{0}; |
| 112 | std::mutex functorMutex; |
| 113 | std::function<void()> safeFunctor; |
| 114 | |
| 115 | // Set the functor to a lambda with manual synchronization |
| 116 | { |
| 117 | std::lock_guard<std::mutex> lock (functorMutex); |
| 118 | safeFunctor = [&callCount]() |
| 119 | { |
| 120 | callCount.fetch_add (1); |
| 121 | std::cout << "Thread-safe function called #" << callCount.load() << "\n"; |
| 122 | std::this_thread::sleep_for (std::chrono::milliseconds (100)); |
| 123 | }; |
| 124 | } |
| 125 | |
| 126 | // Call it from multiple threads |
| 127 | std::vector<std::thread> threads; |
| 128 | |
| 129 | for (int i = 0; i < 3; ++i) |
| 130 | { |
| 131 | threads.emplace_back ([&]() |
| 132 | { |
| 133 | std::cout << "Thread " << i << " calling function...\n"; |
| 134 | std::lock_guard<std::mutex> lock (functorMutex); |
| 135 | if (safeFunctor) |
| 136 | safeFunctor(); |
| 137 | }); |
| 138 | } |
| 139 | |
| 140 | // Wait for threads to complete |
| 141 | for (auto& t : threads) |
| 142 | t.join(); |
| 143 | |
| 144 | // Change the functor while demonstrating thread safety |
| 145 | std::cout << "Changing function implementation safely...\n"; |
| 146 | { |
| 147 | std::lock_guard<std::mutex> lock (functorMutex); |
| 148 | |
| 149 | safeFunctor = [&callCount]() |
| 150 | { |
| 151 | callCount.fetch_add (1); |
| 152 | std::cout << "NEW thread-safe function implementation called #" << callCount.load() << "\n"; |
| 153 | }; |
| 154 | } |
| 155 | |
| 156 | // Call the new implementation |
| 157 | { |
| 158 | std::lock_guard<std::mutex> lock (functorMutex); |
| 159 | |
| 160 | if (safeFunctor) |
| 161 | safeFunctor(); |
| 162 | } |
| 163 | |
| 164 | std::cout << "Thread-safe function was called " << callCount.load() << " times total\n"; |
no test coverage detected