Two cores, one counter: why counter++ loses updates on ESP32

Two FreeRTOS tasks, one on each core of an ESP32-S3, each add 1 to the same global counter a million times. The board reports 1,609,490 instead of 2,000,000. counter++ is three instructions, not one, and the other core can run its own three in between.

In short

  • Two tasks on cores 0 and 1, 1,000,000 increments each: a plain counter++ in a function gave 1,609,490, a volatile counter gave 1,020,310 (about half lost). The exact numbers change from run to run.
  • counter++ compiles to load, add 1, store. volatile only forces the memory accesses; it does not make them atomic.
  • One core is not safe either: with both tasks on core 1 the volatile counter still lost 326,182 increments.
  • Cost per increment with two tasks on two cores: unprotected 18 cycles (wrong), std::atomic 52, portENTER_CRITICAL 227, FreeRTOS mutex about 2,900–3,800, a local counter per task practically 0.
  • A plain counter in a tight loop gave exactly 2,000,000: the compiler folded the loop into one addition. A simple test can hide the bug.

Two million expected, 1,609,490 counted

The test is a model of a typical event counter: a global variable and a small function that increments it. Two tasks call that function a million times each.

uint32_t counter = 0;
void onEvent() { counter++; }

// task A on core 0, task B on core 1:
for (int i = 0; i < 1000000; i++) onEvent();

Both tasks start at the same moment, so the expected total is 2,000,000. On an ESP32-S3 at 240 MHz with arduino-esp32 3.3.12 and default settings, the board printed:

counter = 1609490
expected: 2000000
lost:      390510   (about 20 %)

Almost 400,000 increments disappeared. Nothing crashed and no error was reported; the number is simply wrong.

Two cores, really in parallel

The ESP32-S3 has two Xtensa LX7 cores running at up to 240 MHz. In ESP-IDF's FreeRTOS each core schedules its own tasks independently, so tasks on different cores really run at the same time, not by taking turns.

In Arduino, setup() and loop() run in a FreeRTOS task called loopTask. The core creates it on ARDUINO_RUNNING_CORE, and for the ESP32-S3 the default in the Arduino Runs On menu is core 1:

// arduino-esp32, cores/esp32/main.cpp
xTaskCreateUniversal(loopTask, "loopTask", ..., ARDUINO_RUNNING_CORE);

A second task can be started on core 0 with xTaskCreatePinnedToCore(). Its last parameter sets the core affinity: 0, 1 or tskNO_AFFINITY.

xTaskCreatePinnedToCore(task, "B", 4096, NULL, 2, NULL, 0);   // core 0

Both cores share the same SRAM, so both tasks see the same global counter.

Why increments get lost

counter++ looks like one operation, but the compiler turns it into three instructions. This is the disassembly of onEvent() from the same build (xtensa-esp32s3-elf-objdump -d):

l32r    a9, <counter>    ; address of counter
l32i.n  a8, a9, 0        ; load
addi.n  a8, a8, 1        ; add 1
s32i.n  a8, a9, 0        ; store

Load the value into a register, add one, store it back. Between the load and the store the value lives only in a register of one core. If the other core does the same thing at the same time, both work with the old value:

StepCore 0Core 1counter in RAM
loada8 = 41a8 = 4141
add 1a8 = 42a8 = 4241
storewrites 42writes 4242

Two increments happened, but the counter moved by one. Repeat that a million times on each core and hundreds of thousands of increments are gone.

volatile doesn't help

The usual first guess is to declare the counter volatile. It doesn't help. volatile only forces the compiler to read and write memory on every access instead of keeping the value in a register. cppreference puts it directly:

cppreference: cv type qualifiers

“This makes volatile objects suitable for communication with a signal handler, but not with another thread of execution.”

The disassembly of the loop with a volatile uint32_t counter shows the same three steps, now surrounded by memw memory barriers:

memw
l32i.n  a9, a10, 0       ; load vcounter
addi.n  a8, a8, 1        ; i++
addi.n  a9, a9, 1        ; +1
memw
s32i.n  a9, a10, 0       ; store vcounter

Still load, add, store, with a window in between. In the test it was even worse than the function version:

volatile counter = 1020310
lost: 979690   (about 49 %)

The loop with volatile is tighter than the one that calls onEvent() (18 cycles per increment against 33), so a larger share of the time falls between the read and the write, and more updates collide.

A tight loop can hide the bug

The obvious first test is a plain counter incremented directly in a loop:

uint32_t counter = 0;
for (uint32_t i = 0; i < N; i++) counter++;

With two tasks on two cores this gave exactly 2,000,000, with no losses. The code is not correct; the compiler simply removed the race window. At -Os it counts in a register and does a single counter += N after the loop: one l32i / add / s32i for the whole test. In an earlier build where N was a compile-time constant, the loop measured 0 cycles per increment.

A passing test is not proof

Real code is rarely that simple. In this test, moving the increment into a function that is not inlined was enough for the race to come back. That is why the main test uses onEvent().

One core isn't safe either

Two cores make the race easy to hit, but pinning both tasks to one core does not remove it. If the scheduler switches from task A to task B between A's load and store, A later stores a stale value and overwrites everything B added in the meantime.

With both tasks on core 1 at the same priority:

Mode, both tasks on core 1ResultLost
volatile1,673,818326,182 (≈ 16 %)
onEvent(), first run1,834,512165,488
onEvent(), next runs1,989,65610,344
atomic, critical, mutex, local2,000,0000

An interrupt that lands between the load and the store and touches the same variable does the same thing. That case was not measured here. The ESP-IDF documentation describes critical sections as protecting a shared resource from other tasks and from ISRs alike.

Fix 1: std::atomic

std::atomic<uint32_t> counter{0};
counter++;

In this Arduino build the atomic ++ does not become a single inline instruction. It compiles to a call (callx8) to the library function __atomic_fetch_add_4, and the actual increment is done in __atomic_s32c1i_fetch_add_4:

memw
l32i.n   a9, a2, 0          ; read the old value
loop:
mov.n    a2, a9
add.n    a10, a9, a3        ; new = old + 1
wsr.scompare1 a9            ; SCOMPARE1 = expected old value
s32c1i   a10, a8, 0         ; store only if memory still holds the old value
mov.n    a9, a10
bne      a10, a2, loop      ; no match: try again

The core of it is S32C1I, the Xtensa conditional store. The ISA summary describes it as: “Stores to a location only if the location contains the value in the SCOMPARE1 register. The comparison of the old value and the store, if equal, is atomic.” The ESP32-S3 has it (XCHAL_HAVE_S32C1I 1 in ESP-IDF's core-isa.h).

So the increment is a compare-and-swap loop: read the old value, compute the new one, store it only if memory still holds the old value. If the other core got there first, s32c1i returns a different value, and the loop tries again with the fresh one. No update is ever overwritten.

Result: 2,000,000, every time. Cost: about 52 cycles per increment with two tasks on two cores, against 18 for the unprotected volatile version.

Fix 2: critical section

portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mux);  counter++;  portEXIT_CRITICAL(&mux);

On a dual-core chip a critical section does two things. From the ESP-IDF FreeRTOS documentation:

ESP-IDF: FreeRTOS (IDF), Critical Sections

“The core disables its interrupts or interrupt nesting up to configMAX_SYSCALL_INTERRUPT_PRIORITY.” · “The core then spins on the spinlock using an atomic compare-and-set instruction until it acquires the lock.”

Interrupts are disabled only on the current core; the spinlock keeps the other core out. Inside the section the increment is still the ordinary memw / l32i / addi / memw / s32i, between calls to vPortEnterCritical and vPortExitCritical, but now nothing can get in between.

Result: 2,000,000. Cost: about 227 cycles per increment on two cores. Because interrupts are masked for the whole section, the documentation also says: “Critical sections should be kept as short as possible” and “The longer the critical section lasts, the longer a pending interrupt can be delayed.”

Fix 3: FreeRTOS mutex

xSemaphoreTake(mtx, portMAX_DELAY);  counter++;  xSemaphoreGive(mtx);

Also correct: 200,000 out of 200,000. But with two cores fighting over the mutex on every single increment, it cost 2,878 and 3,755 cycles per increment (one number per task), roughly 3,300 on average. Even with a single task and no contention it took 943 cycles.

The mutex test used 100,000 increments per task instead of a million. With a million, the task watchdog brought the board down: the idle task on core 0 (IDLE0) got no CPU time for 5 seconds (CONFIG_ESP_TASK_WDT_TIMEOUT_S=5, CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y).

A mutex makes sense when the protected work is long. For one counter it is the most expensive option by far.

Fix 4: don't share

Often the best fix is not to share the variable at all. Each task counts in its own local variable and adds it to the shared total once, at the end:

uint32_t local = 0;
for (uint32_t i = 0; i < N; i++) local++;
total += local;   // once; total is a std::atomic

Result: 2,000,000. Measured cost: 0.0 cycles per increment at the precision of the test. The tasks touch shared memory once each instead of a million times.

What each fix costs

The full measurements. Cycles were counted with esp_cpu_get_cycle_count() around each task's loop and divided by the number of increments.

Two tasks on different cores (0 and 1), 2,000,000 expected

ModeResultLostCycles / increment
plain (tight loop)2,000,000012
plain_fn (onEvent())1,609,490390,510 (≈ 20 %)33
volatile1,020,310979,690 (≈ 49 %)18
atomic2,000,000052
critical2,000,0000227
mutex (N = 100,000)200,00002,878 / 3,755
local2,000,0000≈ 0

One task (cost without contention)

ModeCycles / increment
plain8
plain_fn23
volatile12
atomic49
critical193
mutex943

Comparing the two tables: contention from the other core adds little to the atomic (49 → 52) and the critical section (193 → 227), but makes the mutex three to four times more expensive (943 → 2,878–3,755).

With both tasks on one core, each task's time per increment is roughly twice as long, because the two tasks share one core. That is not the cost of the operation, so those cycle numbers are left out here.

Which one to use

If two tasks, or a task and an interrupt, write the same variable, volatile is not enough. Then:

SituationUse
shared by two tasks, or a task and an ISRvolatile alone is not enough
data can be kept separatelocal counters, combined once
one counter or flagstd::atomic
several values that must change together, short workportENTER_CRITICAL
long work inside the protected sectionmutex

Caveats

Test setup and code

BoardESP32-S3, 2 cores at 240 MHz, 16 MB flash, 8 MB PSRAM (PSRAM disabled in the board menu, the default)
Corearduino-esp32 3.3.12, board esp32:esp32:esp32s3, default settings (-Os, Arduino Runs On: Core 1)
FreeRTOSIDF FreeRTOS, dual-core (CONFIG_FREERTOS_UNICORE and CONFIG_FREERTOS_SMP not set), tick 1 ms (CONFIG_FREERTOS_HZ=1000)
Toolchainarduino-cli from Arduino IDE 2.3.8; disassembly with xtensa-esp32s3-elf-objdump -d of the same build
Methodtwo tasks created with xTaskCreatePinnedToCore(), priority 2, released together by an event group bit; N = 1,000,000 increments each (100,000 for the mutex); cycles via esp_cpu_get_cycle_count() around each task's loop, divided by N; each two-task mode run 3 times

Each mode has its own noinline function, so its disassembly is easy to find. The measurements apply to the ESP32-S3; other chips were not tested.

race.ino (shortened) · full file
#include <atomic>
#include "freertos/event_groups.h"
#include "esp_cpu.h"

uint32_t counter = 0;                 // plain global
volatile uint32_t vcounter = 0;       // volatile global
std::atomic<uint32_t> acounter{0};    // atomic
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
SemaphoreHandle_t mtx;

// One function per mode, so the disassembly of each is easy to find.
void __attribute__((noinline)) work_plain()    { for (uint32_t i = 0; i < N; i++) counter++; }
// Realistic case: counter++ in a function that is called from the loop
void __attribute__((noinline)) onEvent() { counter++; }
void __attribute__((noinline)) work_plainfn()  { for (uint32_t i = 0; i < N; i++) onEvent(); }
void __attribute__((noinline)) work_volatile() { for (uint32_t i = 0; i < N; i++) vcounter++; }
void __attribute__((noinline)) work_atomic()   { for (uint32_t i = 0; i < N; i++) acounter++; }
void __attribute__((noinline)) work_critical() {
  for (uint32_t i = 0; i < N; i++) { portENTER_CRITICAL(&mux); vcounter++; portEXIT_CRITICAL(&mux); }
}
void __attribute__((noinline)) work_mutex() {
  for (uint32_t i = 0; i < N; i++) { xSemaphoreTake(mtx, portMAX_DELAY); vcounter++; xSemaphoreGive(mtx); }
}
void __attribute__((noinline)) work_local() {
  uint32_t local = 0;
  for (uint32_t i = 0; i < N; i++) local++;
  acounter += local;
}

void worker(void *p) {
  Arg *a = (Arg *)p;
  xEventGroupWaitBits(eg, 1, pdFALSE, pdTRUE, portMAX_DELAY);   // start together
  a->core = xPortGetCoreID();
  uint32_t t0 = esp_cpu_get_cycle_count();
  switch (a->mode) {
    case PLAINFN: work_plainfn(); break;
    // ... one case per mode
  }
  a->cycles = esp_cpu_get_cycle_count() - t0;
  xSemaphoreGive(done);
  vTaskDelete(NULL);
}

// ntasks: 1 or 2; coreB: core of the second task
void run(Mode m, int ntasks, int coreA, int coreB) {
  N = (m == MUTEX) ? N_MUTEX : N_DEFAULT;
  counter = 0; vcounter = 0; acounter = 0;
  xEventGroupClearBits(eg, 1);
  Arg args[2] = {{m, 0, -1}, {m, 0, -1}};
  xTaskCreatePinnedToCore(worker, "wA", 4096, &args[0], 2, NULL, coreA);
  if (ntasks == 2) xTaskCreatePinnedToCore(worker, "wB", 4096, &args[1], 2, NULL, coreB);
  vTaskDelay(pdMS_TO_TICKS(20));
  xEventGroupSetBits(eg, 1);
  for (int i = 0; i < ntasks; i++) xSemaphoreTake(done, portMAX_DELAY);
  // ... print result, expected, lost and cycles per increment
}

void setup() {
  // ... Serial, event group, semaphores
  for (int m = 0; m < NMODES; m++) run((Mode)m, 1, 1, 1);                            // one task
  for (int r = 0; r < 3; r++) for (int m = 0; m < NMODES; m++) run((Mode)m, 2, 0, 1); // cores 0 and 1
  for (int r = 0; r < 3; r++) for (int m = 0; m < NMODES; m++) run((Mode)m, 2, 1, 1); // both on core 1
}

void loop() { delay(1000); }

Sources

  1. ESP32-S3 Series Datasheet “Xtensa® dual-core 32-bit LX7 microprocessor” · “Clock speed: up to 240 MHz”
  2. ESP-IDF v5.5: FreeRTOS (IDF), ESP32-S3, SMP, task creation and critical sections “each core independently schedules tasks to run” · “…PinnedToCore() … extra xCoreID parameter that is used to specify the created task's core affinity” · “The core then spins on the spinlock using an atomic compare-and-set instruction until it acquires the lock.” · “Critical sections should be kept as short as possible”
  3. Cadence: Xtensa Instruction Set Architecture (ISA) Summary, §4.3.13.2 “Exclusive Access with the S32C1I Instruction” “S32C1I — Store 32-Bit compare conditional. Stores to a location only if the location contains the value in the SCOMPARE1 register. The comparison of the old value and the store, if equal, is atomic.”
  4. cppreference: cv (const and volatile) type qualifiers “This makes volatile objects suitable for communication with a signal handler, but not with another thread of execution.”
  5. arduino-esp32: cores/esp32/main.cpp and boards.txt (version 3.3.12) xTaskCreateUniversal(loopTask, "loopTask", …, ARDUINO_RUNNING_CORE); Arduino Runs On, first entry Core 1 → -DARDUINO_RUNNING_CORE=1
  6. ESP-IDF v5.5.6 source: components/xtensa/esp32s3/include/xtensa/config/core-isa.h XCHAL_HAVE_S32C1I 1
  7. Random Nerd Tutorials: How to use ESP32 Dual Core with Arduino IDE by default, setup() and loop() run on core 1

Video

A short video on the same topic is on the ESPSSS YouTube channel (3:49, 2026-11-18). This page goes into more detail.

Also as a YouTube Short.