MCPcopy Create free account
hub / github.com/Tracktion/choc / demonstrateSpinLock

Function demonstrateSpinLock

examples/threading_patterns.cpp:62–105  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

60}
61
62void 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
107void demonstrateThreadSafeFunctor()
108{

Callers 1

mainFunction · 0.85

Calls 2

loadMethod · 0.80
emplace_backMethod · 0.80

Tested by

no test coverage detected