| 60 | } |
| 61 | |
| 62 | void demonstrateSpinLock() |
| 63 | { |
| 64 | std::cout << "\n=== SpinLock Demo ===\n"; |
| 65 | |
| 66 | choc::threading::SpinLock spinLock; |
| 67 | std::atomic<int> sharedCounter{0}; |
| 68 | std::vector<std::thread> threads; |
| 69 | constexpr int numThreads = 4; |
| 70 | constexpr int incrementsPerThread = 1000; |
| 71 | |
| 72 | auto workerFunction = [&](int threadId) |
| 73 | { |
| 74 | for (int i = 0; i < incrementsPerThread; ++i) |
| 75 | { |
| 76 | // Critical section protected by spin lock |
| 77 | { |
| 78 | std::scoped_lock lock (spinLock); |
| 79 | int current = sharedCounter.load(); |
| 80 | // Simulate some work |
| 81 | std::this_thread::sleep_for (std::chrono::microseconds (1)); |
| 82 | sharedCounter.store (current + 1); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | std::cout << "Thread " << threadId << " completed\n"; |
| 87 | }; |
| 88 | |
| 89 | auto startTime = std::chrono::steady_clock::now(); |
| 90 | |
| 91 | // Start worker threads |
| 92 | for (int i = 0; i < numThreads; ++i) |
| 93 | threads.emplace_back (workerFunction, i); |
| 94 | |
| 95 | // Wait for all threads to complete |
| 96 | for (auto& t : threads) |
| 97 | t.join(); |
| 98 | |
| 99 | auto endTime = std::chrono::steady_clock::now(); |
| 100 | auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime); |
| 101 | |
| 102 | std::cout << "SpinLock test completed in " << duration.count() << "ms\n"; |
| 103 | std::cout << "Expected: " << (numThreads * incrementsPerThread) << ", Actual: " << sharedCounter.load() << "\n"; |
| 104 | std::cout << "Result: " << (sharedCounter.load() == numThreads * incrementsPerThread ? "PASS" : "FAIL") << "\n"; |
| 105 | } |
| 106 | |
| 107 | void demonstrateThreadSafeFunctor() |
| 108 | { |
no test coverage detected