CONCURRENCY & OS INTERNALS

C++11 Concurrency | Multi-Threaded Architecture | Synchronization Pipelines

Christopher Wilt - Systems Engineer

SYSTEMS MULTITHREADING LAB ARCHIVE

01. Asynchronous Pipelines (Promises & Futures)

Tackled decoupling data production loops from data display operations, engineering asynchronous communication avenues across thread barriers without explicit locking stalls.

Architected a nested thread hierarchy where primary active workers spawn specialized, localized logging sub-threads. Leveraged std::promise and std::future data configurations to transport execution metrics. Moving (std::move) tracking tokens directly into sub-contexts allows long-running asynchronous threads to report final numeric tallies securely without blocking execution pathways.

Managed safe thread cleanups for detached asynchronous environments by enforcing a structural, mutex-locked tracking system. The main thread delegates work and sleeps via a conditional variable block (cv.wait), instantly waking to free array heap structures only when the active thread tally reaches zero.

// Asynchronous Pipeline Flow
[Worker Thread] ---> Resolve Promise
                           |
                           v (Data Tunnel)
[Printer Thread] <--- Collect Future (.get)

02. Race Condition Analysis & Deterministic Execution

Engineered an evaluation framework explicitly designed to illustrate shared-memory corruption hazards, implementing strict synchronization mechanisms to override OS non-determinism.

Developed an executable environment capable of hot-swapping between unsynchronized operations (inducing data collisions across a shared text vector) and highly synchronized critical sections guarded by scoped std::unique_lock barriers. Optimized lock-scoping borders to protect memory mutations while minimizing thread-blocking stall windows.

To prove thread scheduling control, the engine purposefully spawns execution threads in reverse chronological order, but forces a forward-sequential, orderly execution loop. Threads evaluate runtime index states using lambda conditions, instantly sleeping via a condition variable cascade if out of sequence.

// 1. Spawning threads in reverse chronological order
for (int i = threadCount - 1; i >= 0; i--) {
    perThreadData[i].id = i;
    threads.emplace_back(ThreadEntryPoint, &perThreadData[i]);
}

// 2. Forcing forward-sequential execution (Inside Worker)
std::unique_lock<std::mutex> lock(*threadData->sharedMutex);

// Lambda condition evaluates runtime index state
threadData->conditionVar->wait(lock, [&]() {
    return threadData->id == *threadData->currentThread;
});

/* --- CRITICAL SECTION (Memory Mutation) --- */

// Increment turn and cascade wake-up to next thread
*threadData->currentThread = (*threadData->currentThread + 1) % threadCount;
threadData->conditionVar->notify_all();

03. Turn-Based Coordination & Variadic Thread-Safe Logging

Designed a strict turn-based alternating worker execution matrix, isolating and resolving hardware I/O resource contention across detached tracking processes.

Engineered a dual-thread coordinating routine forcing alternating execution phases across a single shared board memory context. Threads pass system access tokens using conditional handshakes, executing notify_all() calls to toggle state parameters without burning CPU cycles on polling spinlocks.

Resolved console output corruption by building a custom, synchronized variadic logging mechanism. Wrapping variadic print buffers (va_list, vprintf) inside an internal static mutex wrapper completely guarantees that interleaved string streams from hundreds of concurrent processes do not shatter text data structures.

// 1. Thread locks mutex and waits for its specific turn
std::unique_lock<std::mutex> lock(*threadData->sharedMutex);

threadData->conditionVar->wait(lock, [&]() {
    return threadData->id == *threadData->currentThread;
});

/* --- CRITICAL SECTION (Thread-Safe Operation) --- */
printf("RunType 3 - Thread %d: %s\n", 
    threadData->id, threadData->sharedString);

// 2. Pass the baton to the next thread in sequence
*threadData->currentThread = (*threadData->currentThread + 1) % threadData->threadCount;

// 3. Notify all waiting threads to re-evaluate condition
threadData->conditionVar->notify_all();

04. Bitwise Resource Allocation Scheduling

Architected a high-concurrency resource tracking and dispatch system modeled after kernel-level memory management paradigms, bypassing bulky software objects in favor of bitmasking operations.

Replaced array-based allocations by managing up to 32 concurrent hardware contexts inside a single, memory-optimized 32-bit unsigned integer (freeMask). Implemented atomic bitwise operations—utilizing shifts, bitwise AND/OR, and bitwise NOT logic—to evaluate availability states and alter allocation parameters instantaneously.

Integrated condition variable thread queues to throttle access when bit availability fills completely. When an execution thread finishes, it clears its respective bit mapping and triggers a broad notify_all() call, prompting waiting worker contexts to validate allocations without runtime lag spikes.

// 1. Await Available Bit in 32-bit Integer
std::unique_lock<std::mutex> lock(resourceMutex);
cv.wait(lock, [&]() { return freeMask != 0; });

// 2. Find and Claim Resource (Bitwise AND / NOT)
int bitIndex = 0;
while ((freeMask & (1 << bitIndex)) == 0) {
    bitIndex++;
}
freeMask &= ~(1 << bitIndex); // Flip specific bit to 0 (Claimed)
lock.unlock();

/* --- EXECUTE HARDWARE CONTEXT --- */

// 3. Release Resource & Notify (Bitwise OR)
lock.lock();
freeMask |= (1 << bitIndex); // Flip specific bit back to 1 (Free)
cv.notify_all();

05. Deadlock Mitigation & Synchronization Barriers

Analyzed and resolved severe synchronization failures within highly contested shared-memory parameters by rewriting resource-locking paradigms to destroy the conditions required for a deadlock.

Modeled a variation of the classic "Dining Philosophers" concurrency crisis. Eliminated circular wait hazards by constructing a hybrid non-blocking/blocking resource claim routine. Workers successfully block on primary assets via lock(), but inspect secondary adjacent items using non-blocking try_lock() calls; if a conflict triggers, the thread explicitly abandons all items and yields, resolving contention.

Implemented synchronization barriers using condition blocks to prevent premature thread execution. Spawns threads into a suspended state, validating memory pooling maps completely before issuing a parallel notification wave to guarantee pristine concurrent load-testing environments.

// 1. Synchronization Barrier (Suspend until all threads ready)
std::unique_lock<std::mutex> syncLock(syncMutex);
if (++readyCount == totalThreads) {
    startBarrier.notify_all();
} else {
    startBarrier.wait(syncLock);
}
syncLock.unlock();

// 2. Hybrid Locking Routine to Prevent Deadlock
while (true) {
    primaryMutex.lock(); // Blocking claim on primary asset
    
    // Non-blocking inspection of secondary asset
    if (secondaryMutex.try_lock()) { 
        /* --- EXECUTE CRITICAL SECTION --- */
        secondaryMutex.unlock();
        primaryMutex.unlock();
        break; 
    } else {
        // Conflict detected: Abandon claims and yield CPU
        primaryMutex.unlock();
        std::this_thread::yield(); 
    }
}