CppCommon  1.0.4.1
C++ Common Library
threads_spin_lock.cpp

Spin-lock synchronization primitive example

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
std::cout << "Press Enter to stop..." << std::endl;
// Start some threads
std::atomic<bool> stop(false);
std::vector<std::thread> threads;
for (int thread = 0; thread < 4; ++thread)
{
threads.emplace_back([&lock, &stop, thread]()
{
while (!stop)
{
// Use locker with spin-lock to protect the output
std::cout << "Random value from thread " << thread << ": " << rand() << std::endl;
}
});
}
// Wait for input
std::cin.get();
// Stop threads
stop = true;
// Wait for all threads
for (auto& thread : threads)
thread.join();
return 0;
}
Locker synchronization primitive.
Definition: locker.h:23
Spin-lock synchronization primitive.
Definition: spin_lock.h:30
Spin-lock synchronization primitive definition.