Support kit: thread safety

Support kit: thread safety

  • mdo  DigitalBox
  •   KitLab
  •   April 13, 2026

In the previous KitLab article, we explored object serialization with BArchivable.

Now let's tackle one of the most critical aspects of modern programming: thread safety.

When multiple threads access shared data simultaneously, race conditions can cause unpredictable behavior, data corruption, and crashes.

Haiku's BLocker and BAutolock provide elegant solutions to protect shared resources and ensure thread-safe access.

Understanding thread synchronization is essential for any application using background tasks, timers, or parallel processing.

What is BLocker?

BLocker is Haiku's mutual exclusion (mutex) primitive.

It ensures that only one thread can access a protected resource at a time.

Core concept: When a thread locks a BLocker, all other threads attempting to lock it must wait until it's unlocked.

BLocker locker("my_lock");

locker.Lock();
// Critical section - only one thread at a time
shared_data++;
locker.Unlock();

What is BAutolock?

BAutolock is a helper class that makes BLocker easier and safer to use.

It automatically locks when created and unlocks when destroyed.

BLocker locker("my_lock");
{
    BAutolock autolock(locker);
    // Lock acquired automatically
    shared_data++;
    // Lock released automatically when autolock goes out of scope
}

Why use BAutolock?

  • The unlock is guaranteed when leaving the "{}" block, even if an error occurs, the code crashes, or you return early from the function
  • It's impossible to forget unlocking
  • The code is cleaner and more readable

Race Conditions

Consider this simple counter increment:

// WITHOUT locking (UNSAFE!)
int32 counter = 0;

// Thread 1
counter++;

// Thread 2  
counter++;

What should happen?

The counter should end up at 2 after both threads finish.

What actually happens?

The result is unpredictable and depends on timing—it could be 1 or 2. This occurs because counter++ isn't a single atomic operation.

Instead, it consists of three steps:

  • reading the current value
  • adding 1
  • writing the new value back to memory.

When both threads read the counter before either has written their result, they end up writing the same value, causing one increment to be lost.

Mutual Exclusion needed

BLocker locker;
int32 counter = 0;

// Thread 1
{
    BAutolock lock(locker);
    counter++;  // Protected
}

// Thread 2
{
    BAutolock lock(locker);
    counter++;  // Protected
}

In the above code, always 2 is guaranteed!

Only one thread can execute the critical section at a time up to BAutoLock.

Demo: Thread-Safe Counter

We'll create an interactive counter application that demonstrates:

  • Multiple threads incrementing/decrementing a shared counter
  • BLocker protection ensuring thread safety
  • Race conditions when locking is disabled
  • BAutolock for automatic lock management
  • Real-time visualization of thread activity

This shows thread safety problems and solutions in action.

Source Code: ThreadCounter.cpp

// ThreadCounter.cpp - Demonstrates BLocker and BAutolock for thread safety

#include <Application.h>
#include <Window.h>
#include <View.h>
#include <Button.h>
#include <StringView.h>
#include <CheckBox.h>
#include <Locker.h>
#include <Autolock.h>
#include <OS.h>
#include <String.h>
#include <stdio.h>

const uint32 MSG_INCREMENT = 'INCR';
const uint32 MSG_DECREMENT = 'DECR';
const uint32 MSG_FAST_INCREMENT = 'FINC';
const uint32 MSG_RESET = 'RSET';
const uint32 MSG_UPDATE_DISPLAY = 'UPDT';
const uint32 MSG_TOGGLE_LOCKING = 'LOCK';

// Shared counter with thread-safe access
class ThreadSafeCounter {
public:
    ThreadSafeCounter()
        : fValue(0),
          fLocker("counter_lock"),
          fUseLocking(true)
    {
    }

    void Increment() {
        if (fUseLocking) {
            // Thread-safe version using BAutolock
            BAutolock autolock(fLocker);
            fValue++;
        } else {
            // UNSAFE: No locking (for demonstration)
            fValue++;
        }
    }

    void Decrement() {
        if (fUseLocking) {
            // Thread-safe version using BAutolock
            BAutolock autolock(fLocker);
            fValue--;
        } else {
            // UNSAFE: No locking
            fValue--;
        }
    }

    void Reset() {
        BAutolock autolock(fLocker);
        fValue = 0;
    }

    int32 GetValue() {
        if (fUseLocking) {
            BAutolock autolock(fLocker);
            return fValue;
        } else {
            // UNSAFE: No locking
            return fValue;
        }
    }

    void SetUseLocking(bool useLocking) {
        BAutolock autolock(fLocker);
        fUseLocking = useLocking;
    }

    bool UseLocking() const {
        return fUseLocking;
    }

private:
    int32 fValue;
    BLocker fLocker;
    bool fUseLocking;
};

// Thread function for incrementing
int32 increment_thread(void* data) {
    ThreadSafeCounter* counter = (ThreadSafeCounter*)data;

    // Increment 250 times with small delays
    for (int i = 0; i < 250; i++) {
        counter->Increment();

        // Small delay to increase chance of race conditions
        snooze(100);  // 0.1 milliseconds
    }

    return 0;
}

// Thread function for decrementing
int32 decrement_thread(void* data) {
    ThreadSafeCounter* counter = (ThreadSafeCounter*)data;

    // Decrement 250 times with small delays
    for (int i = 0; i < 250; i++) {
        counter->Decrement();
        snooze(100);
    }

    return 0;
}

// Thread function for fast increments (shows race conditions better)
int32 fast_increment_thread(void* data) {
    ThreadSafeCounter* counter = (ThreadSafeCounter*)data;

    // Rapid increments without delays
    for (int i = 0; i < 2500; i++) {
        counter->Increment();
    }

    return 0;
}

class CounterView : public BView {
public:
    CounterView(BRect frame)
        : BView(frame, "counter_view", B_FOLLOW_ALL, B_WILL_DRAW),
          fCounter(new ThreadSafeCounter()),
          fActiveThreads(0)
    {
        SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));

        BRect bounds = Bounds();
        float left = 10;
        float right = bounds.right - 10;
        float top = 10;

        // Title
        BStringView* title = new BStringView(
            BRect(left, top, right, top + 20),
            "title", "Thread-Safe Counter - BLocker Demo",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        title->SetFont(be_bold_font);
        AddChild(title);
        top += 35;

        // Counter display
        fCounterView = new BStringView(
            BRect(left, top, right, top + 40),
            "counter", "Counter: 0",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        fCounterView->SetFont(be_bold_font);
        fCounterView->SetFontSize(28);
        AddChild(fCounterView);
        top += 55;

        // Thread count display
        fThreadView = new BStringView(
            BRect(left, top, right, top + 20),
            "threads", "Active threads: 0",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        AddChild(fThreadView);
        top += 30;

        // Locking status
        fLockingView = new BStringView(
            BRect(left, top, right, top + 20),
            "locking", "Thread safety: ENABLED",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        AddChild(fLockingView);
        top += 35;

        // Locking toggle
        fLockingCheck = new BCheckBox(
            BRect(left, top, right, top + 25),
            "lockcheck", "Use thread-safe locking (BAutolock)",
            new BMessage(MSG_TOGGLE_LOCKING),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        fLockingCheck->SetValue(B_CONTROL_ON);
        AddChild(fLockingCheck);
        top += 40;

        // Info text
        BStringView* info = new BStringView(
            BRect(left, top, right, top + 60),
            "info",
            "Try disabling locking and running Fast Increment\n"
            "multiple times. Race conditions will cause incorrect\n"
            "results. With locking enabled, the counter is always accurate.",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        info->SetFontSize(10);
        AddChild(info);
        top += 70;

        // Buttons row 1
        fIncrementButton = new BButton(
            BRect(left, top, left + 140, top + 30),
            "inc", "Increment (1000x)",
            new BMessage(MSG_INCREMENT),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fIncrementButton);

        fDecrementButton = new BButton(
            BRect(left + 150, top, left + 290, top + 30),
            "dec", "Decrement (1000x)",
            new BMessage(MSG_DECREMENT),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fDecrementButton);
        top += 40;

        // Buttons row 2
        fFastButton = new BButton(
            BRect(left, top, left + 140, top + 30),
            "fast", "Fast Increment (10k)",
            new BMessage(MSG_FAST_INCREMENT),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fFastButton);

        fResetButton = new BButton(
            BRect(left + 150, top, left + 290, top + 30),
            "reset", "Reset Counter",
            new BMessage(MSG_RESET),
            B_FOLLOW_LEFT | B_FOLLOW_TOP);
        AddChild(fResetButton);
        top += 50;

        // Explanation
        BStringView* explanation = new BStringView(
            BRect(left, top, right, top + 80),
            "explain",
            "BLocker provides mutual exclusion - only one thread can\n"
            "access the protected resource at a time.\n\n"
            "BAutolock automatically locks on creation and unlocks\n"
            "on destruction (RAII pattern).",
            B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
        explanation->SetFontSize(10);
        AddChild(explanation);

        // Start update thread
        StartUpdateThread();
    }

    ~CounterView() {
        fUpdateThreadRunning = false;

        status_t status;
        wait_for_thread(fUpdateThread, &status);

        delete fCounter;
    }

    void AttachedToWindow() override {
        BView::AttachedToWindow();

        fIncrementButton->SetTarget(this);
        fDecrementButton->SetTarget(this);
        fFastButton->SetTarget(this);
        fResetButton->SetTarget(this);
        fLockingCheck->SetTarget(this);
    }

    void MessageReceived(BMessage* message) override {
        switch (message->what) {
            case MSG_INCREMENT:
                LaunchIncrementThread();
                break;

            case MSG_DECREMENT:
                LaunchDecrementThread();
                break;

            case MSG_FAST_INCREMENT:
                LaunchFastIncrementThread();
                break;

            case MSG_RESET:
                ResetCounter();
                break;

            case MSG_UPDATE_DISPLAY:
                UpdateDisplay();
                break;

            case MSG_TOGGLE_LOCKING:
                ToggleLocking();
                break;

            default:
                BView::MessageReceived(message);
                break;
        }
    }

private:
    void LaunchIncrementThread() {
        // Launch 4 threads increment in parallel
        for (int i = 0; i < 4; i++) {
            atomic_add((int32*)&fActiveThreads, 1);
            thread_id thread = spawn_thread(increment_thread, "increment",
                                            B_NORMAL_PRIORITY, fCounter);
            resume_thread(thread);

            spawn_thread(monitor_thread, "monitor", B_NORMAL_PRIORITY,
                         new MonitorData{this, thread});
        }
    }

    void LaunchDecrementThread() {
        // Launch 4 threads decrement in parallel
        for (int i = 0; i < 4; i++) {
            atomic_add((int32*)&fActiveThreads, 1);
            thread_id thread = spawn_thread(decrement_thread, "decrement",
                                            B_NORMAL_PRIORITY, fCounter);
            resume_thread(thread);

            spawn_thread(monitor_thread, "monitor", B_NORMAL_PRIORITY,
                         new MonitorData{this, thread});
        }
    }

    void LaunchFastIncrementThread() {
        // Launch 4 threads in parallel
        for (int i = 0; i < 4; i++) {
            atomic_add((int32*)&fActiveThreads, 1);
            thread_id thread = spawn_thread(fast_increment_thread, "fast_increment",
                                            B_NORMAL_PRIORITY, fCounter);
            resume_thread(thread);

            spawn_thread(monitor_thread, "monitor", B_NORMAL_PRIORITY,
                         new MonitorData{this, thread});
        }
    }

    void ResetCounter() {
        fCounter->Reset();
        UpdateDisplay();
    }

    void ToggleLocking() {
        bool enabled = (fLockingCheck->Value() == B_CONTROL_ON);
        fCounter->SetUseLocking(enabled);

        if (enabled) {
            fLockingView->SetText("Thread safety: ENABLED ✓");
        } else {
            fLockingView->SetText("Thread safety: DISABLED ⚠ (UNSAFE!)");
        }
    }

    void UpdateDisplay() {
        int32 value = fCounter->GetValue();

        BString text;
        text << "Counter: " << value;
        fCounterView->SetText(text.String());

        text = "";
        text << "Active threads: " << fActiveThreads;
        fThreadView->SetText(text.String());
    }

    void StartUpdateThread() {
        fUpdateThreadRunning = true;
        fUpdateThread = spawn_thread(update_thread, "update_display",
                                      B_NORMAL_PRIORITY, this);
        resume_thread(fUpdateThread);
    }

    // Thread to periodically update display
    static int32 update_thread(void* data) {
        CounterView* view = (CounterView*)data;

        while (view->fUpdateThreadRunning) {
            BMessage msg(MSG_UPDATE_DISPLAY);
            BMessenger(view).SendMessage(&msg);
            snooze(100000);  // Update every 0.1 seconds
        }

        return 0;
    }

    // Monitor thread completion
    struct MonitorData {
        CounterView* view;
        thread_id thread;
    };

    static int32 monitor_thread(void* data) {
        MonitorData* monitorData = (MonitorData*)data;

        status_t status;
        wait_for_thread(monitorData->thread, &status);

        atomic_add((int32*)&monitorData->view->fActiveThreads, -1);

        delete monitorData;
        return 0;
    }

    ThreadSafeCounter* fCounter;
    vint32 fActiveThreads;

    BStringView* fCounterView;
    BStringView* fThreadView;
    BStringView* fLockingView;
    BCheckBox* fLockingCheck;
    BButton* fIncrementButton;
    BButton* fDecrementButton;
    BButton* fFastButton;
    BButton* fResetButton;

    thread_id fUpdateThread;
    volatile bool fUpdateThreadRunning;
};

class CounterWindow : public BWindow {
public:
    CounterWindow(BRect frame)
        : BWindow(frame, "Thread-Safe Counter",
                  B_TITLED_WINDOW,
                  B_QUIT_ON_WINDOW_CLOSE | B_NOT_RESIZABLE)
    {
        BRect viewRect = Bounds();
        CounterView* view = new CounterView(viewRect);
        AddChild(view);
    }
};

class CounterApp : public BApplication {
public:
    CounterApp()
        : BApplication("application/x-vnd.example-ThreadCounter")
    {
        BRect rect(100, 100, 500, 500);
        CounterWindow* window = new CounterWindow(rect);
        window->Show();
    }
};

int main() {
    CounterApp app;
    app.Run();
    return 0;
}

The complete source code is available in the artifact above.

How It Works

Here are the key concepts:

Thread-Safe Counter Class

The ThreadSafeCounter class demonstrates how to protect shared data from concurrent access.

It wraps an integer counter with a  BLocker to ensure only one thread can modify it at a time.

class ThreadSafeCounter {
public:
    ThreadSafeCounter()
        : fValue(0),
          fLocker("counter_lock"),
          fUseLocking(true)
    {
    }

    void Increment() {
        if (fUseLocking) {
            BAutolock autolock(fLocker);  // Automatic locking
            fValue++;
        } else {
            fValue++;  // UNSAFE - for demonstration
        }
    }

    int32 GetValue() {
        BAutolock autolock(fLocker);
        return fValue;
    }

private:
    int32 fValue;
    BLocker fLocker;
    bool fUseLocking;
};

Worker Threads

Worker threads are independent execution contexts that perform repetitive operations on the shared counter.

Each thread runs this function:

int32 increment_thread(void* data) {
    ThreadSafeCounter* counter = (ThreadSafeCounter*)data;

    // Increment 250 times with small delays
    for (int i = 0; i < 250; i++) {
        counter->Increment();

        // Small delay to increase chance of race conditions
        snooze(100);  // 0.1 milliseconds
    }

    return 0;
}

Launching Threads

To demonstrate race conditions more effectively, each button click launches 4 threads in parallel.

This significantly increases the chances of concurrent access conflicts:

    void LaunchIncrementThread() {
        // Launch 4 threads increment in parallel
        for (int i = 0; i < 4; i++) {
            atomic_add((int32*)&fActiveThreads, 1);
            thread_id thread = spawn_thread(increment_thread, "increment",
                                            B_NORMAL_PRIORITY, fCounter);
            resume_thread(thread);

            spawn_thread(monitor_thread, "monitor", B_NORMAL_PRIORITY,
                         new MonitorData{this, thread});
        }
    }

Compilation

gcc ThreadCounter.cpp -o ThreadCounter -lbe

Running the Demo

./ThreadCounter

You'll see:

  • A large counter display
  • Buttons to launch increment/decrement threads
  • Active thread counter
  • Thread safety toggle checkbox

Try this:

With locking enabled (default):

Click "Increment (1000x)" multiple times rapidly

The counter increases correctly by 1,000 each time and no lost updates.

Now disable the locking:

    Then click "Increment (1000x)" multiple times rapidly:

    On my system, the counter shows correct results meaning I didn't succeed to have race conditions.

    However it could happen.

    Let's do another try.

    Click "Fast Increment (10k)" multiple times rapidly:

    As you can see, the counter shows incorrect results (race conditions encountered)

    The updates are lost due to concurrent access.

    Now reset the counter:

    Tick again "Use thread-safe locking"

    Then click "Fast Increment (10k)" multiple times rapidly:

    The counter shows correct results (multiple of 10000) because of the thread-safe lock enabled:)

    Conclusion

    Thread safety is not optional in modern applications. Race conditions cause subtle bugs that are notoriously difficult to reproduce and debug.

    BLocker and BAutolock make thread safety straightforward.

    The pattern is simple: protect shared data with a BLocker, and always use BAutolock for automatic lock management. 

    Master thread safety now, and save yourself from countless hours of debugging mysterious, timing-dependent bugs later.

    Remember: if data is shared between threads, it must be protected:)

    Stay tuned for the next KitLab article!


    Powered by Bludit - Hosted by Planet Hoster
    © 2025 Haiku Insider