Skip to content

Synchronization: Atomic counters #2302

@jnohlgard

Description

@jnohlgard

We currently have atomic_set_return() for atomic variables used by e.g. mutexes.
This works well for a simple on/off mutex lock, but not for counter variables, since the value to set must be computed before calling atomic_set_return().

What are your opinions on adding this kind of functionality to the core atomic API?

Below is an example of an implementation of an increment/decrement function for an atomic counter without disabling interrupts (for a Cortex-M CPU):

static inline void exclusive_increment(volatile uint32_t* value) {
  int status;
  int tmp;
  do {
    /* Load exclusive */
    tmp = __LDREXW(value);

    /* increment counter */
    ++tmp;

    /* Try to write the new value */
    status = __STREXW(tmp, value);
  } while (status != 0); /* retry until load-store cycle was exclusive. */
}

The STREX instruction returns non-zero if an interrupt (or context switch) occurred between the LDREX and the STREX instructions.

I guess the simplest initial implementation for any other CPUs would be to disable interrupts beforehand and enable them afterwards.

Metadata

Metadata

Assignees

Labels

Area: coreArea: RIOT kernel. Handle PRs marked with this with care!Discussion: RFCThe issue/PR is used as a discussion starting point about the item of the issue/PRProcess: API changeIntegration Process: PR contains or issue proposes an API change. Should be handled with care.Type: enhancementThe issue suggests enhanceable parts / The PR enhances parts of the codebase / documentationType: new featureThe issue requests / The PR implemements a new feature for RIOT

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions