### Thread Management with Synch Framework Source: https://context7.com/nkallima/synch-framework/llms.txt Demonstrates creating and managing POSIX threads using the Synch framework's threadtools API. It showcases setting NUMA-aware thread placement policies, initializing a barrier, starting worker threads, and joining them. The example highlights thread identification, preferred core assignment, and atomic operations like Fetch-And-Add. ```c #include #include #include #define N_THREADS 8 SynchBarrier bar; int64_t result; void *worker_function(void *arg) { int id = synchGetThreadId(); int core = synchGetPreferredCore(); printf("Thread %d running on core %d\n", id, core); synchBarrierWait(&bar); // Perform work... synchFAA64(&result, 1); synchBarrierWait(&bar); return NULL; } int main(void) { result = 0; // Set NUMA-aware thread placement policy synchSetThreadPlacementPolicy(SYNCH_THREAD_PLACEMENT_NUMA_SPARSE); // Initialize barrier for N_THREADS synchBarrierSet(&bar, N_THREADS); // Start N_THREADS POSIX threads without fibers synchStartThreadsN(N_THREADS, worker_function, SYNCH_DONT_USE_UTHREADS); // Wait for all threads to complete synchJoinThreadsN(N_THREADS); printf("Result: %ld\n", result); // Output: Result: 8 return 0; } ``` -------------------------------- ### CC-Stack Concurrent Stack API Example Source: https://context7.com/nkallima/synch-framework/llms.txt Provides a blocking concurrent stack implementation utilizing the CC-Synch combining technique. This example demonstrates efficient push and pop operations across multiple threads. It depends on ccstack.h, threadtools.h, barrier.h, and primitives.h. ```c #include #include #include #include #define N_THREADS 4 #define OPS_PER_THREAD 5000 CCStackStruct *stack; SynchBarrier bar; void *stack_worker(void *arg) { CCStackThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCStackThreadState)); CCStackThreadStateInit(stack, th_state, id); synchBarrierWait(&bar); for (int i = 0; i < OPS_PER_THREAD; i++) { // Push: add element to top of stack CCStackPush(stack, th_state, id * 1000 + i, id); // Pop: remove element from top of stack RetVal popped = CCStackPop(stack, th_state, id); // Note: popped may be EMPTY_STACK if stack was empty } synchBarrierWait(&bar); return NULL; } int main(void) { stack = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCStackStruct)); // Initialize concurrent stack CCStackInit(stack, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, stack_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Stack operations completed successfully\n"); return 0; } ``` -------------------------------- ### Atomic Primitives Demo with Synch Framework Source: https://context7.com/nkallima/synch-framework/llms.txt Illustrates the use of atomic operations provided by the Synch primitives API, including Fetch-And-Add (FAA) and Compare-And-Swap (CAS). It also demonstrates memory barriers for ensuring visibility and checking processor architecture. The example uses threads and barriers to coordinate concurrent access to shared variables. ```c #include #include #include volatile int64_t counter = 0; volatile int64_t cas_counter = 0; SynchBarrier bar; void *atomic_ops_demo(void *arg) { int id = synchGetThreadId(); synchBarrierWait(&bar); // Fetch-And-Add: atomically increment counter by 10 int64_t old_val = synchFAA64(&counter, 10); printf("Thread %d: FAA returned %ld\n", id, old_val); // Compare-And-Swap: try to update cas_counter from 0 to id bool success = synchCAS64(&cas_counter, 0, id); if (success) { printf("Thread %d won the CAS race\n", id); } // Memory fence for visibility synchFullFence(); synchBarrierWait(&bar); return NULL; } int main(void) { // Get processor information uint64_t machine = synchGetMachineModel(); if (machine == AMD_X86_MACHINE) { printf("Running on AMD processor\n"); } else if (machine == INTEL_X86_MACHINE) { printf("Running on Intel processor\n"); } // Allocate aligned memory int64_t *data = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(int64_t) * 100); synchBarrierSet(&bar, 4); synchStartThreadsN(4, atomic_ops_demo, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(4); printf("Final counter: %ld\n", counter); // Output: Final counter: 40 synchFreeMemory(data, sizeof(int64_t) * 100); return 0; } ``` -------------------------------- ### P-Sim Wait-Free Universal Construction API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements P-Sim, a wait-free universal construction that simulates sequential data structures with guaranteed bounded operation steps. It requires threadtools and barrier libraries. The example demonstrates a wait-free increment operation. ```c #include #include #include #define N_THREADS 8 #define OPERATIONS 50000 typedef struct { int64_t counter; } SimState; RetVal sim_increment(void *state, ArgVal arg, int pid) { SimState *s = (SimState *)state; s->counter += arg; return s->counter; } SimStruct *sim; SynchBarrier bar; void *sim_worker(void *arg) { SimThreadState th_state; int id = synchGetThreadId(); // Initialize thread state with number of threads SimThreadStateInit(&th_state, N_THREADS, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { // Wait-free operation Object result = SimApplyOp(sim, &th_state, sim_increment, 1, id); } synchBarrierWait(&bar); return NULL; } int main(void) { sim = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(SimStruct)); // Initialize Sim with max backoff of 100 synchSimStructInit(sim, N_THREADS, 100); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, sim_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Wait-free Sim operations completed\n"); return 0; } ``` -------------------------------- ### Barrier Synchronization with Synch Framework Source: https://context7.com/nkallima/synch-framework/llms.txt Demonstrates the use of the Synch barrier API for re-entrant synchronization between threads. The example shows multiple phases of computation where threads synchronize at the end of each phase using `synchBarrierWait`. It illustrates how barriers ensure all threads reach a certain point before proceeding, coordinating phased computations. ```c #include #include #include #define PHASES 3 #define NUM_THREADS 4 SynchBarrier bar; int64_t phase_results[PHASES]; void *phased_computation(void *arg) { int id = synchGetThreadId(); for (int phase = 0; phase < PHASES; phase++) { // Each thread contributes to phase computation synchFAA64(&phase_results[phase], id + 1); // All threads synchronize before moving to next phase synchBarrierWait(&bar); if (id == 0) { printf("Phase %d complete, result: %ld\n", phase, phase_results[phase]); } synchBarrierWait(&bar); // Ensure print completes } return NULL; } int main(void) { for (int i = 0; i < PHASES; i++) { phase_results[i] = 0; } // Initialize re-entrant barrier synchBarrierSet(&bar, NUM_THREADS); synchStartThreadsN(NUM_THREADS, phased_computation, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(NUM_THREADS); // Output: // Phase 0 complete, result: 10 // Phase 1 complete, result: 10 // Phase 2 complete, result: 10 return 0; } ``` -------------------------------- ### CC-Queue Concurrent Queue API Example Source: https://context7.com/nkallima/synch-framework/llms.txt Implements a blocking concurrent queue using the CC-Synch combining technique. This example showcases high-throughput enqueue and dequeue operations performed by multiple producer-consumer threads. It requires ccqueue.h, threadtools.h, barrier.h, and primitives.h. ```c #include #include #include #include #define N_THREADS 4 #define ITEMS_PER_THREAD 10000 CCQueueStruct *queue; SynchBarrier bar; void *producer_consumer(void *arg) { CCQueueThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCQueueThreadState)); CCQueueThreadStateInit(queue, th_state, id); synchBarrierWait(&bar); for (int i = 0; i < ITEMS_PER_THREAD; i++) { // Enqueue: add item to back of queue ArgVal item = id * ITEMS_PER_THREAD + i; CCQueueApplyEnqueue(queue, th_state, item, id); // Dequeue: remove item from front of queue RetVal dequeued = CCQueueApplyDequeue(queue, th_state, id); // Note: dequeued may be EMPTY_QUEUE if queue was empty } synchBarrierWait(&bar); return NULL; } int main(void) { queue = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCQueueStruct)); // Initialize concurrent queue CCQueueStructInit(queue, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, producer_consumer, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Queue operations completed successfully\n"); return 0; } ``` -------------------------------- ### CC-Synch Combining Object API Example Source: https://context7.com/nkallima/synch-framework/llms.txt Demonstrates the CC-Synch combining object for reducing contention on shared data structures. It uses a custom sequential function to increment a shared counter across multiple threads. Dependencies include ccsynch.h, threadtools.h, barrier.h, and primitives.h. ```c #include #include #include #include #define N_THREADS 8 #define OPERATIONS 100000 // Custom sequential function to be executed by the combiner typedef struct { int64_t value; } Counter; RetVal increment_counter(void *state, ArgVal arg, int pid) { Counter *c = (Counter *)state; c->value += arg; return c->value; } CCSynchStruct *combiner; Counter *shared_counter; SynchBarrier bar; void *ccsynch_worker(void *arg) { CCSynchThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCSynchThreadState)); CCSynchThreadStateInit(combiner, th_state, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { // Apply operation through combining object RetVal result = CCSynchApplyOp(combiner, th_state, increment_counter, shared_counter, 1, // increment by 1 id); } synchBarrierWait(&bar); return NULL; } int main(void) { combiner = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(CCSynchStruct)); shared_counter = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(Counter)); shared_counter->value = 0; // Initialize CC-Synch combining object CCSynchStructInit(combiner, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, ccsynch_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Final counter: %ld\n", shared_counter->value); // Output: Final counter: 800000 return 0; } ``` -------------------------------- ### GET /synch/thread-placement Source: https://github.com/nkallima/synch-framework/blob/main/README.md Retrieves the currently active thread placement policy used by the framework. ```APIDOC ## GET /synch/thread-placement ### Description Returns the current thread placement policy identifier configured in the Synch framework. ### Method GET ### Endpoint /synch/thread-placement ### Response #### Success Response (200) - **policy** (string) - The identifier of the current policy (e.g., SYNCH_THREAD_PLACEMENT_NUMA_SPARSE_SMT_PREFER) #### Response Example { "policy": "SYNCH_THREAD_PLACEMENT_NUMA_SPARSE_SMT_PREFER" } ``` -------------------------------- ### Run Synch Framework Benchmarks with Various Configurations Source: https://context7.com/nkallima/synch-framework/llms.txt This script executes benchmarks for different concurrent data structures within the Synch framework. It allows customization of thread count, operations, and specific algorithm configurations like user-level threads (fibers) or backoff tuning. Dependencies include the benchmark executable and configuration files. ```bash # Run CC-Queue benchmark with default settings ./bench.sh benchmarks/ccqueuebench.run # Run with custom thread count and operations ./bench.sh benchmarks/ccstackbench.run -t 16 -r 1000000 # Run with user-level threads (fibers) for Osci algorithms ./bench.sh benchmarks/osciqueuebench.run -t 8 -f 4 # Run MS-Queue with backoff tuning ./bench.sh benchmarks/msqueuebench.run -t 8 -bl 0 -b 10 # Run H-Synch with custom NUMA configuration ./bench.sh benchmarks/hsynchbench.run -t 32 -n 2 ``` -------------------------------- ### P-Sim Wait-Free Universal Construction API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides a wait-free universal construction that simulates sequential data structures, ensuring operations complete in a bounded number of steps. ```APIDOC ## P-Sim Wait-Free Universal Construction API P-Sim (or Sim) is a wait-free universal construction that can simulate any sequential data structure, guaranteeing that every operation completes in a bounded number of steps. ### Description This API allows the simulation of sequential operations in a wait-free manner, guaranteeing progress for all threads. ### Initialization - `synchSimStructInit(SimStruct *sim, int n_threads, int max_backoff)`: Initializes the Sim structure with the number of threads and maximum backoff. - `SimThreadStateInit(SimThreadState *th_state, int n_threads, int id)`: Initializes the thread-specific state for Sim operations. ### Operations - `SimApplyOp(SimStruct *sim, SimThreadState *th_state, RetVal (*op)(void *state, ArgVal arg, int pid), ArgVal arg, int pid)`: Applies a given operation to the simulated structure in a wait-free manner. ### Example Usage ```c #include #include #include #define N_THREADS 8 #define OPERATIONS 50000 typedef struct { int64_t counter; } SimState; RetVal sim_increment(void *state, ArgVal arg, int pid) { SimState *s = (SimState *)state; s->counter += arg; return s->counter; } SimStruct *sim; SynchBarrier bar; void *sim_worker(void *arg) { SimThreadState th_state; int id = synchGetThreadId(); // Initialize thread state with number of threads SimThreadStateInit(&th_state, N_THREADS, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { // Wait-free operation SimApplyOp(sim, &th_state, sim_increment, 1, id); } synchBarrierWait(&bar); return NULL; } int main(void) { sim = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(SimStruct)); // Initialize Sim with max backoff of 100 synchSimStructInit(sim, N_THREADS, 100); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, sim_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Wait-free Sim operations completed\n"); return 0; } ``` ``` -------------------------------- ### Benchmark Fetch&Add Performance in C Source: https://github.com/nkallima/synch-framework/blob/main/README.md A C implementation that uses the Synch framework to spawn threads and perform atomic Fetch&Add operations on a shared 64-bit integer. It utilizes barriers to synchronize thread execution and measures throughput in millions of operations per second. ```c #include #include #include #include #include #define N_THREADS 10 #define RUNS 1000000 volatile int64_t object CACHE_ALIGN; int64_t d1 CACHE_ALIGN, d2; SynchBarrier bar CACHE_ALIGN; inline static void *Execute(void *Arg) { long i, id; id = synchGetThreadId(); synchBarrierWait(&bar); if (id == 0) d1 = synchGetTimeMillis(); for (i = 0; i < RUNS; i++) synchFAA64(&object, 1); synchBarrierWait(&bar); if (id == 0) d2 = synchGetTimeMillis(); return NULL; } int main(int argc, char *argv[]) { object = 1; synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, Execute, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("time: %ld (ms)\tthroughput: %.2f (millions ops/sec)\n", (d2 - d1), RUNS * N_THREADS / (1000.0 * (d2 - d1))); return 0; } ``` -------------------------------- ### POST /synch/thread-placement Source: https://github.com/nkallima/synch-framework/blob/main/README.md Updates the thread placement policy to optimize execution based on hardware architecture. ```APIDOC ## POST /synch/thread-placement ### Description Sets the thread placement policy to one of the supported strategies to control thread allocation across processors. ### Method POST ### Endpoint /synch/thread-placement ### Request Body - **policy** (string) - Required - The policy constant (e.g., SYNCH_THREAD_PLACEMENT_FLAT, SYNCH_THREAD_PLACEMENT_NUMA_DENSE) ### Request Example { "policy": "SYNCH_THREAD_PLACEMENT_NUMA_DENSE" } ### Response #### Success Response (200) - **status** (string) - Confirmation message of the policy update. ``` -------------------------------- ### Execute Synch Framework Validation and Smoke Tests Source: https://context7.com/nkallima/synch-framework/llms.txt These scripts are used to validate the correctness of the Synch framework and perform quick smoke tests across all benchmarks. The `validate.sh` script checks for functional correctness, while `run_all.sh` provides a rapid overview of benchmark performance. ```bash # Run validation tests ./validate.sh # Quick smoke test for all benchmarks ./run_all.sh ``` -------------------------------- ### Flat-Combining (FC) API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Provides an efficient flat-combining synchronization technique. A designated combiner thread executes operations on behalf of other threads, reducing contention. Requires fc.h, threadtools.h, and barrier.h. ```c #include #include #include #define N_THREADS 8 #define OPERATIONS 100000 typedef struct { int64_t value; } FCState; RetVal fc_increment(void *state, ArgVal arg, int pid) { FCState *s = (FCState *)state; s->value += arg; return s->value; } FCStruct *fc; FCState *state; SynchBarrier bar; void *fc_worker(void *arg) { FCThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(FCThreadState)); FCThreadStateInit(fc, th_state, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { // Apply operation using flat-combining FCApplyOp(fc, th_state, fc_increment, state, 1, id); } synchBarrierWait(&bar); return NULL; } int main(void) { fc = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(FCStruct)); state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(FCState)); state->value = 0; // Initialize flat-combining object FCStructInit(fc, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, fc_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Value: %ld (expected: %d)\n", state->value, N_THREADS * OPERATIONS); return 0; } ``` -------------------------------- ### Cite Synch Framework BibTeX Source: https://github.com/nkallima/synch-framework/blob/main/README.md BibTeX entry for citing the Synch framework in academic publications. ```latex @article{Kallimanis2021, doi = {10.21105/joss.03143}, url = {https://doi.org/10.21105/joss.03143}, year = {2021}, publisher = {The Open Journal}, volume = {6}, number = {64}, pages = {3143}, author = {Nikolaos D. Kallimanis}, title = {Synch: A framework for concurrent data-structures and benchmarks}, journal = {Journal of Open Source Software} } ``` -------------------------------- ### Backoff API for Contention Management (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements exponential backoff delays for contention management in lock-free algorithms. It provides functions to initialize, delay, increase, reduce, and reset the backoff mechanism. Requires the backoff library. ```c #include int main(void) { SynchBackoffStruct backoff; // Initialize backoff: base=2^2=4, cap=2^8=256, shift=2^1=2 synchInitBackoff(&backoff, 2, 8, 1); // Simulate contention scenario for (int attempt = 0; attempt < 10; attempt++) { bool success = false; // Simulate CAS failure if (!success) { // Apply backoff delay on failure synchBackoffDelay(&backoff); // Increase backoff for next failure synchBackoffIncrease(&backoff); } else { // Reduce backoff on success synchBackoffReduce(&backoff); } } // Reset backoff to initial value synchResetBackoff(&backoff); return 0; } ``` -------------------------------- ### LF-Stack Lock-Free Stack API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements the Treiber lock-free stack. It offers non-blocking push and pop operations, efficient for scenarios requiring stack-like data structures. Dependencies include threadtools and barrier libraries. ```c #include #include #include #define N_THREADS 4 #define OPS 5000 LFStackStruct stack; SynchBarrier bar; void *lfstack_worker(void *arg) { LFStackThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(LFStackThreadState)); // Initialize with backoff: min=0, max=8 LFStackThreadStateInit(th_state, 0, 8); synchBarrierWait(&bar); for (int i = 0; i < OPS; i++) { // Lock-free push LFStackPush(&stack, th_state, id * OPS + i); // Lock-free pop RetVal val = LFStackPop(&stack, th_state); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize lock-free stack LFStackInit(&stack); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, lfstack_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Lock-free stack operations completed\n"); return 0; } ``` -------------------------------- ### H-Synch NUMA-Aware Combining API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides functions for initializing and applying operations to a hierarchical combining object optimized for NUMA architectures. ```APIDOC ## HSynchStructInit ### Description Initializes the H-Synch structure for NUMA-aware synchronization. ### Method Function Call ### Parameters - **hsynch** (HSynchStruct*) - Required - Pointer to the structure to initialize. - **n_threads** (int) - Required - Total number of threads. - **policy** (int) - Required - NUMA policy identifier (e.g., HSYNCH_DEFAULT_NUMA_POLICY). ## HSynchApplyOp ### Description Applies an operation to the shared state using NUMA-aware combining. ### Method Function Call ### Parameters - **hsynch** (HSynchStruct*) - Required - Pointer to the H-Synch object. - **th_state** (HSynchThreadState*) - Required - Thread-local state. - **op** (Function Pointer) - Required - The operation function to execute. - **state** (void*) - Required - Pointer to the shared state. - **arg** (ArgVal) - Required - Argument for the operation. - **pid** (int) - Required - Process/Thread ID. ``` -------------------------------- ### MS-Queue Lock-Free Queue API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements the Michael and Scott lock-free concurrent queue. It provides non-blocking enqueue and dequeue operations suitable for high-contention scenarios. Requires threadtools and barrier libraries for multi-threading support. ```c #include #include #include #define N_THREADS 8 #define ITEMS 10000 MSQueueStruct queue; SynchBarrier bar; void *msqueue_worker(void *arg) { MSQueueThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(MSQueueThreadState)); // Initialize with backoff parameters: min=0, max=10 MSQueueThreadStateInit(th_state, 0, 10); synchBarrierWait(&bar); for (int i = 0; i < ITEMS; i++) { // Lock-free enqueue MSQueueEnqueue(&queue, th_state, id); // Lock-free dequeue RetVal val = MSQueueDequeue(&queue, th_state); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize lock-free queue MSQueueInit(&queue); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, msqueue_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Lock-free queue operations completed\n"); return 0; } ``` -------------------------------- ### H-Synch NUMA-Aware Combining Object API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements a hierarchical combining object optimized for NUMA architectures. It combines operations within NUMA nodes before global synchronization, improving data locality. Dependencies include hsynch.h, threadtools.h, and barrier.h. ```c #include #include #include #define N_THREADS 16 #define OPERATIONS 50000 typedef struct { int64_t sum; } SharedState; RetVal add_to_sum(void *state, ArgVal arg, int pid) { SharedState *s = (SharedState *)state; s->sum += arg; return s->sum; } HSynchStruct *hsynch; SharedState *state; SynchBarrier bar; void *hsynch_worker(void *arg) { HSynchThreadState *th_state; int id = synchGetThreadId(); th_state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(HSynchThreadState)); HSynchThreadStateInit(hsynch, th_state, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { // Apply operation using NUMA-aware combining HSynchApplyOp(hsynch, th_state, add_to_sum, state, 1, id); } synchBarrierWait(&bar); return NULL; } int main(void) { hsynch = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(HSynchStruct)); state = synchGetAlignedMemory(CACHE_LINE_SIZE, sizeof(SharedState)); state->sum = 0; // Initialize H-Synch with default NUMA policy HSynchStructInit(hsynch, N_THREADS, HSYNCH_DEFAULT_NUMA_POLICY); // Or specify number of NUMA regions: HSynchStructInit(hsynch, N_THREADS, 2); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, hsynch_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Sum: %ld (expected: %d)\n", state->sum, N_THREADS * OPERATIONS); return 0; } ``` -------------------------------- ### Pool Memory Allocator API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Provides an efficient thread-local memory allocator for fixed-size objects, optimized for concurrent data structures. It supports initialization, object allocation, recycling, rollback, and destruction. Requires pool and primitives libraries. ```c #include #include typedef struct MyNode { struct MyNode *next; int64_t value; } MyNode; int main(void) { SynchPoolStruct pool; // Initialize pool for MyNode objects int result = synchInitPool(&pool, sizeof(MyNode)); if (result == SYNCH_POOL_INIT_ERROR) { printf("Pool initialization failed\n"); return 1; } // Allocate objects from pool MyNode *node1 = (MyNode *)synchAllocObj(&pool); MyNode *node2 = (MyNode *)synchAllocObj(&pool); if (node1 == SYNCH_POOL_OBJECT_ALLOC_ERROR) { printf("Allocation failed\n"); return 1; } node1->value = 100; node1->next = node2; node2->value = 200; node2->next = NULL; // Recycle objects back to pool for reuse synchRecycleObj(&pool, node2); synchRecycleObj(&pool, node1); // Allocate again (will reuse recycled memory) MyNode *node3 = (MyNode *)synchAllocObj(&pool); printf("Reused node value: %ld\n", node3->value); // May show previous value // Rollback last allocation synchRollback(&pool, 1); // Clean up pool synchDestroyPool(&pool); return 0; } ``` -------------------------------- ### CLH-Hash Concurrent Hash Table API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements a concurrent hash table using CLH locks for fine-grained synchronization on each bucket. It supports thread-safe insertion, searching, and deletion operations. Requires threadtools and barrier libraries. ```c #include #include #include #define N_THREADS 4 #define NUM_CELLS 1024 #define OPERATIONS 10000 CLHHash hash; SynchBarrier bar; void *hash_worker(void *arg) { CLHHashThreadState th_state; int id = synchGetThreadId(); CLHHashThreadStateInit(&hash, &th_state, NUM_CELLS, id); synchBarrierWait(&bar); for (int i = 0; i < OPERATIONS; i++) { int64_t key = id * OPERATIONS + i; int64_t value = key * 2; // Insert key-value pair bool inserted = CLHHashInsert(&hash, &th_state, key, value, id); // Search for key RetVal found = CLHHashSearch(&hash, &th_state, key, id); // Delete key CLHHashDelete(&hash, &th_state, key, id); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize hash table with NUM_CELLS buckets CLHHashStructInit(&hash, NUM_CELLS, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, hash_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Hash table operations completed\n"); return 0; } ``` -------------------------------- ### Atomic Primitives API Source: https://context7.com/nkallima/synch-framework/llms.txt Portable atomic operations including CAS, FAA, and memory barriers for cross-architecture synchronization. ```APIDOC ## Atomic Primitives API ### Description Provides low-level atomic operations and memory fences optimized for x86_64, ARM-V8, and RISC-V architectures. ### Functions - **synchFAA64(ptr, val)**: Atomically adds value to the memory location and returns the old value. - **synchCAS64(ptr, old, new)**: Performs an atomic Compare-And-Swap operation. - **synchFullFence()**: Executes a full memory barrier to ensure visibility. ### Example ```c int64_t old_val = synchFAA64(&counter, 10); bool success = synchCAS64(&cas_counter, 0, id); synchFullFence(); ``` ``` -------------------------------- ### CLH Queue Lock API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Provides a scalable, queue-based CLH spinlock for fair mutual exclusion. It minimizes cache coherence traffic by having threads spin on local memory. Requires threadtools and barrier libraries. ```c #include #include #include #define N_THREADS 8 #define ITERATIONS 10000 CLHLockStruct *lock; int64_t shared_data = 0; SynchBarrier bar; void *clh_worker(void *arg) { int id = synchGetThreadId(); synchBarrierWait(&bar); for (int i = 0; i < ITERATIONS; i++) { // Acquire CLH lock CLHLock(lock, id); // Critical section shared_data++; // Release CLH lock CLHUnlock(lock, id); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize CLH lock lock = CLHLockInit(N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, clh_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Shared data: %ld (expected: %d)\n", shared_data, N_THREADS * ITERATIONS); // Output: Shared data: 80000 (expected: 80000) return 0; } ``` -------------------------------- ### Barrier Synchronization API Source: https://context7.com/nkallima/synch-framework/llms.txt Re-entrant synchronization barriers to coordinate thread execution phases. ```APIDOC ## Barrier Synchronization API ### Description Allows multiple threads to synchronize at specific execution points using re-entrant barriers. ### Functions - **synchBarrierSet(barrier, n)**: Initializes a barrier for n threads. - **synchBarrierWait(barrier)**: Blocks the calling thread until all participating threads reach the barrier. ### Example ```c SynchBarrier bar; synchBarrierSet(&bar, 4); // Inside thread function: synchBarrierWait(&bar); ``` ``` -------------------------------- ### Backoff API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides contention management for lock-free algorithms by implementing exponential backoff delays. ```APIDOC ## Backoff API The backoff API provides contention management for lock-free algorithms by implementing exponential backoff delays. ### Description This API helps manage contention in concurrent operations by introducing delays that increase exponentially upon repeated failures. ### Initialization - `synchInitBackoff(SynchBackoffStruct *backoff, int base_exponent, int cap_exponent, int shift)`: Initializes the backoff mechanism with specified parameters for base, cap, and shift. ### Operations - `synchBackoffDelay(SynchBackoffStruct *backoff)`: Applies a delay based on the current backoff state. - `synchBackoffIncrease(SynchBackoffStruct *backoff)`: Increases the backoff delay for the next attempt. - `synchBackoffReduce(SynchBackoffStruct *backoff)`: Reduces the backoff delay, typically upon successful operation. - `synchResetBackoff(SynchBackoffStruct *backoff)`: Resets the backoff mechanism to its initial state. ### Example Usage ```c #include int main(void) { SynchBackoffStruct backoff; // Initialize backoff: base=2^2=4, cap=2^8=256, shift=2^1=2 synchInitBackoff(&backoff, 2, 8, 1); // Simulate contention scenario for (int attempt = 0; attempt < 10; attempt++) { bool success = false; // Simulate CAS failure if (!success) { // Apply backoff delay on failure synchBackoffDelay(&backoff); // Increase backoff for next failure synchBackoffIncrease(&backoff); } else { // Reduce backoff on success synchBackoffReduce(&backoff); } } // Reset backoff to initial value synchResetBackoff(&backoff); return 0; } ``` ``` -------------------------------- ### Flat-Combining (FC) API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides an efficient synchronization technique where a designated combiner thread executes operations on behalf of others. ```APIDOC ## FCStructInit ### Description Initializes the flat-combining structure. ### Method Function Call ### Parameters - **fc** (FCStruct*) - Required - Pointer to the FC structure. - **n_threads** (int) - Required - Number of participating threads. ## FCApplyOp ### Description Submits an operation to be executed by the combiner thread. ### Method Function Call ### Parameters - **fc** (FCStruct*) - Required - Pointer to the FC object. - **th_state** (FCThreadState*) - Required - Thread-local state. - **op** (Function Pointer) - Required - Operation function. - **state** (void*) - Required - Shared state pointer. - **arg** (ArgVal) - Required - Operation argument. - **pid** (int) - Required - Thread ID. ``` -------------------------------- ### Thread Management API Source: https://context7.com/nkallima/synch-framework/llms.txt Functions for creating, managing, and setting placement policies for POSIX threads and user-level fibers. ```APIDOC ## Thread Management API ### Description Provides functionality for managing thread lifecycles and NUMA-aware placement policies. ### Functions - **synchSetThreadPlacementPolicy(policy)**: Sets the thread placement strategy (e.g., SYNCH_THREAD_PLACEMENT_NUMA_SPARSE). - **synchStartThreadsN(n, func, flags)**: Spawns N threads executing the provided function. - **synchJoinThreadsN(n)**: Waits for N threads to complete execution. - **synchGetThreadId()**: Returns the unique identifier for the calling thread. ### Example ```c synchSetThreadPlacementPolicy(SYNCH_THREAD_PLACEMENT_NUMA_SPARSE); synchStartThreadsN(8, worker_function, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(8); ``` ``` -------------------------------- ### MCS Queue Lock API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt Implements the MCS lock, a queue-based spinlock designed for scalability and reduced cache coherence overhead. Threads spin on local memory, improving performance in multi-core systems. Requires threadtools and barrier libraries. ```c #include #include #include #define N_THREADS 8 #define ITERATIONS 10000 MCSLockStruct *lock; int64_t counter = 0; SynchBarrier bar; void *mcs_worker(void *arg) { MCSThreadState th_state; int id = synchGetThreadId(); // Initialize thread-local MCS state MCSThreadStateInit(&th_state, id); synchBarrierWait(&bar); for (int i = 0; i < ITERATIONS; i++) { // Acquire MCS lock MCSLock(lock, &th_state, id); // Critical section counter++; // Release MCS lock MCSUnlock(lock, &th_state, id); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize MCS lock lock = MCSLockInit(); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, mcs_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("Counter: %ld (expected: %d)\n", counter, N_THREADS * ITERATIONS); return 0; } ``` -------------------------------- ### LF-Stack Lock-Free Stack API Source: https://context7.com/nkallima/synch-framework/llms.txt Implements the Treiber lock-free stack for non-blocking push and pop operations. ```APIDOC ## LF-Stack Lock-Free Stack API ### Description Provides a lock-free stack implementation using the Treiber algorithm. ### Method C Function Calls ### Endpoint lfstack.h ### Parameters #### Request Body - **stack** (LFStackStruct*) - Required - Pointer to the stack structure - **th_state** (LFStackThreadState*) - Required - Thread-local state ### Request Example LFStackPush(&stack, th_state, value); ### Response #### Success Response (200) - **val** (RetVal) - The popped value ``` -------------------------------- ### LCRQ High-Performance Queue API (C) Source: https://context7.com/nkallima/synch-framework/llms.txt A high-performance, lock-free concurrent queue optimized for x86 processors with 128-bit CAS support. It achieves exceptional throughput for enqueue and dequeue operations. Requires lcrq.h, threadtools.h, and barrier.h. ```c #include #include #include #define N_THREADS 8 #define ITEMS 50000 LCRQStruct queue; SynchBarrier bar; void *lcrq_worker(void *arg) { LCRQThreadState th_state; int id = synchGetThreadId(); // Initialize thread state LCRQThreadStateInit(&th_state, id); synchBarrierWait(&bar); for (int i = 0; i < ITEMS; i++) { // High-performance enqueue LCRQEnqueue(&queue, &th_state, id * ITEMS + i, id); // High-performance dequeue RetVal val = LCRQDequeue(&queue, &th_state, id); } synchBarrierWait(&bar); return NULL; } int main(void) { // Initialize LCRQ queue LCRQInit(&queue, N_THREADS); synchBarrierSet(&bar, N_THREADS); synchStartThreadsN(N_THREADS, lcrq_worker, SYNCH_DONT_USE_UTHREADS); synchJoinThreadsN(N_THREADS); printf("LCRQ operations completed\n"); return 0; } ``` -------------------------------- ### MS-Queue Lock-Free Queue API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides non-blocking enqueue and dequeue operations using the Michael-Scott algorithm with contention management via backoff. ```APIDOC ## MS-Queue Lock-Free Queue API ### Description Implements the Michael-Scott lock-free concurrent queue for non-blocking operations. ### Method C Function Calls ### Endpoint msqueue.h ### Parameters #### Request Body - **queue** (MSQueueStruct*) - Required - Pointer to the queue structure - **th_state** (MSQueueThreadState*) - Required - Thread-local state with backoff parameters ### Request Example MSQueueEnqueue(&queue, th_state, id); ### Response #### Success Response (200) - **val** (RetVal) - The dequeued value or status ``` -------------------------------- ### LCRQ High-Performance Queue API Source: https://context7.com/nkallima/synch-framework/llms.txt Provides lock-free concurrent queue operations optimized for x86 architectures. ```APIDOC ## LCRQEnqueue ### Description Enqueues an item into the lock-free queue. ### Method Function Call ### Parameters - **queue** (LCRQStruct*) - Required - Pointer to the queue. - **th_state** (LCRQThreadState*) - Required - Thread-local state. - **item** (int64_t) - Required - Data to enqueue. - **id** (int) - Required - Thread ID. ## LCRQDequeue ### Description Dequeues an item from the lock-free queue. ### Method Function Call ### Parameters - **queue** (LCRQStruct*) - Required - Pointer to the queue. - **th_state** (LCRQThreadState*) - Required - Thread-local state. - **id** (int) - Required - Thread ID. ```