{"id":34794448,"url":"https://github.com/llxisdsh/cc","last_synced_at":"2026-04-20T05:08:04.501Z","repository":{"id":329003827,"uuid":"1117700879","full_name":"llxisdsh/cc","owner":"llxisdsh","description":"Concurrent Core for Go — a lightweight, high-performance toolkit designed for critical paths where latency and allocation matter.","archived":false,"fork":false,"pushed_at":"2026-04-15T12:38:05.000Z","size":626,"stargazers_count":10,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-15T14:32:24.621Z","etag":null,"topics":["concurrent","hashmap","lock-free","map","primitive","sync"],"latest_commit_sha":null,"homepage":"https://llxisdsh.github.io/cc/","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/llxisdsh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-16T17:30:57.000Z","updated_at":"2026-04-15T12:38:09.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/llxisdsh/cc","commit_stats":null,"previous_names":["llxisdsh/cc"],"tags_count":21,"template":false,"template_full_name":null,"purl":"pkg:github/llxisdsh/cc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llxisdsh%2Fcc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llxisdsh%2Fcc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llxisdsh%2Fcc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llxisdsh%2Fcc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/llxisdsh","download_url":"https://codeload.github.com/llxisdsh/cc/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/llxisdsh%2Fcc/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32033739,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-20T00:18:06.643Z","status":"online","status_checked_at":"2026-04-20T02:00:06.527Z","response_time":94,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["concurrent","hashmap","lock-free","map","primitive","sync"],"created_at":"2025-12-25T10:36:29.651Z","updated_at":"2026-04-20T05:08:04.495Z","avatar_url":"https://github.com/llxisdsh.png","language":"Go","readme":"# **C**oncurrent **C**ore\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/llxisdsh/cc.svg)](https://pkg.go.dev/github.com/llxisdsh/cc)\n\n**Concurrent Core for Go** — a lightweight, high-performance toolkit designed for critical paths where latency and allocation matter.\n\n## Installation\n\n```bash\ngo get github.com/llxisdsh/cc\n```\n\n## Core Components\n\n### 🚀 Concurrent Maps\n\nState-of-the-art concurrent map implementations, delivering extreme performance in a lightweight package.\n\n| Component       | Description                                                                      | Ideal Use Case                                                          |\n|-----------------|----------------------------------------------------------------------------------|-------------------------------------------------------------------------|\n| **`Map`**       | **Lock-free reads**, fine-grained write locking. Drop-in `sync.Map` replacement. | General purpose, mixed R/W workloads.                                   |\n| **`FlatMap`**   | **Seqlock-based**, inline open-addressing. Heavily optimized for cold starts.    | Cache-sensitive, extremely low tail latency.                            |\n| **`SkipMap`**   | **Ordered map**, providing lock-free concurrent lookups, reads, and iteration.   | Highly concurrent ordered data access.                                  |\n| **`FunnelMap`** | **Highly robust**, utilizes SkipMap for collisions and PLocal for size tracking. | Extreme resilience against poor hash distributions without degradation. |\n\n\u003e **Note**: `Map` and `FlatMap` are streamlined versions of the high-performance [**llxisdsh/pb**](https://github.com/llxisdsh/pb) project. For comprehensive benchmarks (throughput, tail latency, memory usage, cold starts) and advanced architectural details, please refer to the [`benchmark`](./benchmark) directory or the upstream repository.\n\n### ⚡ Processor Local\n\n- **`PLocal[T]`**: Processor-local storage. Shards data by P (GOMAXPROCS) to minimize lock contention. Ideal for high-throughput counters or temporary buffers.\n\n### 🧵 Execution Patterns\n\nTools to manage task execution and flow.\n\n- **`WorkerPool`**: Robust, high-performance worker pool with zero-allocation on happy path.\n- **`OnceGroup[K, V]`**: Coalesces duplicate requests (singleflight). \\~20× faster than `singleflight` with panic propagation.\n\n### 🔒 Synchronization Primitives\n\nAtomic, low-overhead coordination tools built on runtime semaphores.\n\n| Primitive             | Metaphor            | Behavior                                                                 | Key Usage                               |\n|:----------------------|:--------------------|:-------------------------------------------------------------------------|:----------------------------------------|\n| **`Latch`**           | **One-time Door**   | Starts closed. Once `Open()`, stays open forever.                        | Initialization, Shutdown signal.        |\n| **`Gate`**            | **Manual Door**     | `Open()`/`Close()`/`Pulse()`. Supports broadcast wakeups.                | Pausing/Resuming, Cond-like signals.    |\n| **`Rally`**           | **Meeting Point**   | `Meet(n)` waits until n parties arrive, then releases all.               | CyclicBarrier, MapReduce stages.        |\n| **`Phaser`**          | **Dynamic Barrier** | Dynamic party registration with split-phase `Arrive()`/`AwaitAdvance()`. | Java-style Phaser, Pipeline stages.     |\n| **`Epoch`**           | **Milestone**       | `WaitAtLeast(n)` blocks until counter reaches n. No thundering herd.     | Phase coordination, Version gates.      |\n| **`Barter`**          | **Exchanger**       | Two goroutines swap values at a sync point.                              | Producer-Consumer handoff.              |\n| **`RWLock`**          | **Read-Write Lock** | Spin-based R/W lock, writer-preferred.                                   | Low-latency, writer-priority.           |\n| **`TicketLock`**      | **Ticket Queue**    | FIFO spin-lock with ticket algorithm.                                    | Fair mutex, Latency-sensitive paths.    |\n| **`BitLock`**         | **Bit Lock**        | Spins on a specific bit mask.                                            | Fine-grained, memory-constrained locks. |\n| **`SeqLock`**         | **Sequence Lock**   | Optimistic reads with version counting.                                  | Tear-free snapshots, Read-heavy.        |\n| **`FairSemaphore`**   | **FIFO Queue**      | Strict FIFO ordering for permit acquisition.                             | Anti-starvation scenarios.              |\n| **`TicketLockGroup`** | **Keyed Lock**      | Per-key locking with auto-cleanup.                                       | User/Resource isolation.                |\n| **`RWLockGroup`**     | **Keyed R/W Lock**  | Per-key R/W locking with auto-cleanup.                                   | Config/Data partitioning.               |\n| **`WaitGroup`**       | **Reusable WG**     | Supports `TryWait()` \u0026 `Waiters()`. Reusable immediately.                | Batch processing.                       |\n\n\u003e **Design Philosophy**: Minimal footprint, direct `runtime_semacquire` integration. Most primitives are zero-alloc on hot paths.\n\n### 🛠️ Concurrency Helpers\n\nGeneric helpers to add Timeout and Context cancellation support to any blocking operation, plus tools for periodic and parallel execution.\n\n- **`Wait` / `WaitTimeout`**: Add Context cancellation or Timeouts to blocking functions.\n- **`Do`**: Execute functions returning errors with Context support.\n- **`Repeat`**: Run actions periodically until Context is cancelled or an error occurs.\n- **`Parallel`**: Execute N tasks concurrently with fail-fast error handling.\n\n## Quick Start\n\n### Concurrent Map\n\n```go\npackage main\n\nimport \"github.com/llxisdsh/cc\"\n\nfunc main() {\n    // 1. Standard Map (Lock-free reads, sync.Map compatible)\n    var m cc.Map[string, int]\n    m.Store(\"foo\", 1)\n\n    // 2. FlatMap (Seqlock-based, inline open-addressing)\n    fm := cc.NewFlatMap[string, int](cc.WithCapacity(1000))\n    fm.Store(\"bar\", 2)\n\n    // 3. SkipMap (Lock-free, ordered concurrent skip list)\n    sm := cc.NewSkipMap[string, int]()\n    sm.Store(\"baz\", 3)\n\n    // 4. FunnelMap (High-throughput, extreme collision resilience)\n    funnel := cc.NewFunnelMap[string, int]()\n    funnel.Store(\"qux\", 4)\n\n    // 5. Compute (Atomic Read-Modify-Write)\n    // Safe, lock-free coordination for complex state changes\n    m.Compute(\"foo\", func(e *cc.MapEntry[string, int]) {\n        if e.Loaded() {\n            // Atomically increment if exists\n            e.Update(e.Value() + 1)\n        } else {\n            // Initialize if missing\n            e.Update(1)\n        }\n    })\n\n    // 6. Rebuild (Atomic transaction)\n    // Safe, Multiple operations as single atomic transaction\n    m.Rebuild(func(r *cc.MapRebuild[string, int]) {\n        r.Store(\"new\", 1)\n        r.Delete(\"old\")\n        r.Compute(\"counter\", func(e *cc.MapEntry[string, int]) {\n            e.Update(e.Value() + 1)\n        })\n    })\n}\n```\n\n### PLocal (Processor-Local Storage)\n\n```go\n// 1. Scalable Counter (PLocalCounter)\nvar c cc.PLocalCounter\n// High throughput: Writes are sharded by P, avoiding global lock contention\nc.Add(1)         // Scalable: No global lock\nsum := c.Value() // Aggregates across all Ps\n\n// 2. Generic PLocal\nvar p cc.PLocal[*bytes.Buffer]\n// Run fn pinned to current P with local shard\np.With(func(buf **bytes.Buffer) {\n    if *buf == nil { *buf = new(bytes.Buffer) }\n    (*buf).WriteString(\"data\")\n})\n```\n\n### WorkerPool\n\n```go\n// Create a pool with 10 workers and queue size of 100\nwp := cc.NewWorkerPool(10, 100)\n\n// Optional: Handle panics from workers\nwp.OnPanic = func(r any) {\n    log.Printf(\"Worker panicked: %v\", r)\n}\n\n// Submit non-blocking task (blocks if queue full)\nwp.Submit(func() {\n    process()\n})\n\n// Wait for all tasks to complete without closing\nwp.Wait()\n\n// Graceful shutdown\nwp.Close()\n```\n\n### OnceGroup\n\n```go\nvar g cc.OnceGroup[string, string]\n// Coalesce duplicate requests\nval, err, shared := g.Do(\"key\", func() (string, error) {\n    return \"expensive-op\", nil\n})\n```\n\n### Concurrency Helpers\n\n```go\n// Wait: Add Context cancellation to a blocking function\nerr := cc.Wait(ctx, func() {\n    wg.Wait()\n})\n\n// WaitTimeout: Add Timeout to a blocking function\nif err := cc.WaitTimeout(time.Second, wg.Wait); err != nil {\n    // timed out\n}\n\n// Do: Execute a function that returns error, with Context support\nerr := cc.Do(ctx, func() error {\n    return complexOp()\n})\n\n// Repeat: Run action periodically until Context cancelled or error\ncc.Repeat(ctx, 5*time.Second, func(ctx context.Context) error {\n    return reloadConfig()\n})\n\n// Parallel: Execute N tasks concurrently (fail-fast on error)\nerr := cc.Parallel(ctx, 10, func(ctx context.Context, i int) error {\n    return processItem(i)\n})\n```\n\n### Primitives Gallery\n\n#### 1. Coordination\n\n```go\n// Latch: One-shot signal (e.g., init finished)\nvar l cc.Latch\ngo func() { l.Open() }()\nl.Wait() // Blocks until Open()\n\n// Gate: Reusable stop/go barrier\nvar g cc.Gate\ng.Open()   // All waiters pass\ng.Close()  // Future waiters block\ng.Pulse()  // Wake current waiters only, remain closed\n\n// Rally: Cyclic barrier for N parties\nvar r cc.Rally\nr.Meet(3)  // Blocks until 3 goroutines arrive\n\n// WaitGroup: Reusable\nvar wg cc.WaitGroup\nwg.Go(func() { /* work */ })\n// Add timeout support via cc.WaitTimeout\nerr := cc.WaitTimeout(time.Second, wg.Wait)\n```\n\n#### 2. Advanced Locking\n\n```go\n// RWLock: Writer-preferred R/W lock (avoids writer starvation)\nvar rw cc.RWLock\nrw.Lock() // Higher priority than RLock\n\n// TicketLock: Fair mutex (FIFO), no starvation\nvar mu cc.TicketLock\nmu.Lock()\ndefer mu.Unlock()\n\n// BitLock: Memory-efficient lock using a single bit in uint64\nvar state uint64\nconst lockBit = 1 \u003c\u003c 63\ncc.BitLockUint64(\u0026state, lockBit) // Spins until bit 63 is 0, then sets it\ncc.BitUnlockUint64(\u0026state, lockBit)\n\n// SeqLock: Tear-free snapshots for read-heavy small data\nvar sl cc.SeqLock\nvar slot cc.SeqLockSlot[string]\ncc.SeqLockWrite(\u0026sl, \u0026slot, \"data\") // Writer\nval := cc.SeqLockRead(\u0026sl, \u0026slot)   // Reader (optimistic, no blocking)\n```\n\n#### 3. Keyed Locks (Auto-cleanup)\n\n```go\n// Lock by key (string, int, etc.) without memory leaks\nvar locks cc.TicketLockGroup[string]\n\nlocks.Lock(\"user:123\")\n// Critical section for user:123\nlocks.Unlock(\"user:123\")\n```\n\n#### 4. Specialized\n\n```go\n// Phaser: Dynamic barrier (Java-style)\np := cc.NewPhaser()\np.Register()\nphase := p.ArriveAndAwaitAdvance()\n\n// Epoch: Wait for counter to reach target (e.g., version waits)\nvar e cc.Epoch\ne.WaitAtLeast(5) // Blocks until e.Add() reaches 5\n\n// Barter: Exchanger for 2 goroutines\nb := cc.NewBarter[string]()\n// G1: b.Exchange(\"ping\") -\u003e returns \"pong\"\n// G2: b.Exchange(\"pong\") -\u003e returns \"ping\"\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fllxisdsh%2Fcc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fllxisdsh%2Fcc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fllxisdsh%2Fcc/lists"}