HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Simple Multithread Timer

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpletimermultithread

Problem

This is a very basic timer that can support multithreading with std::thread and std::chrono.

The timer has the classic functions: start() and stop().

The start() method creates an independent thread (if multithread support is enabled), then sleep the thread for a given Interval, then execute Timeout function. This method sets the running flag to true.

If singleShot flag is not enabled the sleepThenTimeout process is called while a running flag is true.

If multithread support is not enabled, the current thread is sleep.

The stop() method just sets the running flag to false and join the thread.

My doubt is about threat-safety. I've just started to learn how multithreading works, so I'm not sure if I must use mutexes or something like that.

Any other type of feedback are welcome!

Timer.h

#ifndef TIMER_H
#define TIMER_H

#include 
#include 

class Timer
{
public:
    typedef std::chrono::milliseconds Interval;
    typedef std::function Timeout;

    Timer(const Timeout &timeout);
    Timer(const Timeout &timeout,
          const Interval &interval,
          bool singleShot = true);

    void start(bool multiThread = false);
    void stop();

    bool running() const;

    void setSingleShot(bool singleShot);
    bool isSingleShot() const;

    void setInterval(const Interval &interval);
    const Interval &interval() const;

    void setTimeout(const Timeout &timeout);
    const Timeout &timeout() const;

private:
    std::thread _thread;

    bool _running = false;
    bool _isSingleShot = true;

    Interval _interval = Interval(0);
    Timeout _timeout = nullptr;

    void _temporize();
    void _sleepThenTimeout();
};

#endif // TIMER_H


Timer.cpp

```
#include "Timer.h"

Timer::Timer(const Timeout &timeout)
: _timeout(timeout)
{
}

Timer::Timer(const Timer::Timeout &timeout,
const Timer::Interval &interval,
bool singleShot)
: _isSingleShot(singleShot),
_interval(interval),

Solution

Basically you are working with these class members inside the thread functions _temporize and _sleepThenTimeout.

  • timeout, _isSingleShort and _interval, these three cannot be changed after the start function is called, so it is safe to use them.



  • _running on the other hand can be read/write by both threads. In reality it might not cause any problem as assignment to bool is atomic (on most architectures), but to be 100% safe you can use std::atomic.



Another important thing to keep in mind is that while timer class itself is thread safe, it is responsibility of the user of this class to make sure that the timer call back function (_timeout) is thread-safe by it self, as it will be executed in a separate thread.

Context

StackExchange Code Review Q#40915, answer score: 3

Revisions (0)

No revisions yet.