Skip to content

Commit

Permalink
Added a couple of guards
Browse files Browse the repository at this point in the history
  • Loading branch information
berndporr committed Jan 28, 2024
1 parent fa8adb0 commit fcdb3e3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 27 deletions.
52 changes: 28 additions & 24 deletions CppTimer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,12 @@
* This is inspired by the timerfd_create man page.
**/

void CppTimer::worker() {
running = true;
while (running) {
uint64_t exp;
const long int s = read(fd, &exp, sizeof(uint64_t));
if (s != sizeof(uint64_t) ) {
running = false;
return;
}
timerEvent();
}
// disarm
struct itimerspec itsnew;
itsnew.it_value.tv_sec = 0;
itsnew.it_value.tv_nsec = 0;
itsnew.it_interval.tv_sec = 0;
itsnew.it_interval.tv_nsec = 0;
timerfd_settime(fd, 0, &itsnew, &its);
close(fd);
fd = -1;
}

void CppTimer::startns(long nanosecs, cppTimerType_t type)
{
if (running) return;
fd = timerfd_create(CLOCKID, 0);
fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (fd < 0)
throw("Could not start timer");
switch (type)
{
case (PERIODIC):
Expand All @@ -61,7 +41,9 @@ void CppTimer::startns(long nanosecs, cppTimerType_t type)
void CppTimer::startms(long millisecs, cppTimerType_t type)
{
if (running) return;
fd = timerfd_create(CLOCKID, 0);
fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (fd < 0)
throw("Could not start timer");
switch (type)
{
case (PERIODIC):
Expand All @@ -84,6 +66,28 @@ void CppTimer::startms(long millisecs, cppTimerType_t type)
uthread = std::thread(&CppTimer::worker,this);
}

void CppTimer::worker() {
running = true;
while (running) {
uint64_t exp;
const long int s = read(fd, &exp, sizeof(uint64_t));
if (s != sizeof(uint64_t) ) {
running = false;
return;
}
timerEvent();
}
// disarm
struct itimerspec itsnew;
itsnew.it_value.tv_sec = 0;
itsnew.it_value.tv_nsec = 0;
itsnew.it_interval.tv_sec = 0;
itsnew.it_interval.tv_nsec = 0;
timerfd_settime(fd, 0, &itsnew, &its);
close(fd);
fd = -1;
}

void CppTimer::stop()
{
if (!running) return;
Expand Down
3 changes: 0 additions & 3 deletions CppTimer.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <thread>

#define CLOCKID CLOCK_MONOTONIC

/**
* Enumeration of CppTimer types
**/
Expand Down

0 comments on commit fcdb3e3

Please sign in to comment.