Skip to content

Extension of osKernelGetTickCount() to provide monotonic tick counter is in error. #1655

@tobermory

Description

@tobermory

The explanation of the RTOS2 api call osKernelGetTickCount(), at

https://www.keil.com/pack/doc/CMSIS/RTOS2/html/group__CMSIS__RTOS__KernelCtrl.html#ga84bcdbf2fb76b10c8df4e439f0c7e11b

includes a discussion on how to adapt the 32-bit counter, which may rollover, into a 64-bit one which likely will not (or will take much longer to do so). The code presented is

uint64_t GetTick(void) {
  static uint32_t tick_h = 0U;
  static uint32_t tick_l = 0U;
  uint32_t tick;
  tick = osKernelGetTickCount();
  if (tick < tick_l) {
    tick_h++;
  }
  tick_l = tick;
  return (((uint64_t)tick_h << 32) | tick_l);
}

This is not thread-safe. tick_h could be incremented twice, by two threads, for only one physical wrap of the underlying tick counter. The consequence is that, to the calling program, time has jumped forward by 48 days (@ 1ms).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions