CppCommon  1.0.4.1
C++ Common Library
threads_file_lock.cpp

File-lock synchronization primitive example

#include "threads/thread.h"
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
std::cout << "Press Enter to stop..." << std::endl;
CppCommon::FileLock lock_master(".lock");
int current = 0;
std::atomic<bool> stop(false);
// Start some producers threads
std::vector<std::thread> producers;
for (int producer = 0; producer < 4; ++producer)
{
producers.emplace_back([&stop, &current, producer]()
{
CppCommon::FileLock lock_slave(".lock");
while (!stop)
{
// Use a write locker to produce the item
{
current = rand();
std::cout << "Produce value from thread " << producer << ": " << current << std::endl;
}
// Sleep for a while...
}
});
}
// Start some consumers threads
std::vector<std::thread> consumers;
for (int consumer = 0; consumer < 4; ++consumer)
{
consumers.emplace_back([&stop, &current, consumer]()
{
CppCommon::FileLock lock_slave(".lock");
while (!stop)
{
// Use a read locker to consume the item
{
std::cout << "Consume value in thread " << consumer << ": " << current << std::endl;
}
// Sleep for a while...
}
});
}
// Wait for input
std::cin.get();
// Stop threads
stop = true;
// Wait for all producers threads
for (auto& producer : producers)
producer.join();
// Wait for all consumers threads
for (auto& consumer : consumers)
consumer.join();
return 0;
}
File-lock synchronization primitive.
Definition: file_lock.h:34
Read locker synchronization primitive.
Definition: locker.h:50
static void SleepFor(const Timespan &timespan) noexcept
Sleep the current thread for the given timespan.
Definition: thread.cpp:83
int64_t milliseconds() const noexcept
Get total milliseconds of the current timespan.
Definition: timespan.h:141
Write locker synchronization primitive.
Definition: locker.h:77
File-lock synchronization primitive definition.
Thread definition.