c:c_threads:protected_access_to_shared_data_or_shared_resources:atomic_read_write:class_example
Table of Contents
C - C++ Threads - Protected access to shared data or shared resources - Atomic Read & Write - Class Example
start_thread.hpp
#pragma once #include <cstdint> std::int64_t startAndStopThread(int runningMilliseconds, int incrementValue);
start_thread.cpp
#include "start_thread.hpp" #include <atomic> #include <thread> class SampleThreadClass { public: void threadFunction(int inputVal) { while (running) { result += inputVal; } } std::atomic<bool> running{true}; int64_t result{0}; }; int64_t startAndStopThread(int runningMilliseconds, int incrementValue) { SampleThreadClass sampleThreadClass; // Start thread. std::thread t = std::thread(&SampleThreadClass::threadFunction, &sampleThreadClass, incrementValue); // Wait. std::this_thread::sleep_for(std::chrono::milliseconds(runningMilliseconds)); // Stop thread. sampleThreadClass.running = false; t.join(); return sampleThreadClass.result; }
c/c_threads/protected_access_to_shared_data_or_shared_resources/atomic_read_write/class_example.txt · Last modified: 2021/06/08 09:39 by peter