샘플
golang.org/x/sync v0.22.0: errgroup.WithContext, errgroup.Group.SetLimit, semaphore.NewWeighted
검증된 샘플 — golang golang.org/x/sync v0.22.0: errgroup.WithContext, errgroup.Group.SetLimit, semaphore.NewWeighted. go 1.26 · linux alpine/x64 · docker에서…
sha256:b48b87cfb762b19b87a9e14cfa4c246213ffb3bcc3308a534d6e0055f6323576
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 go
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-20 |
케이스
HOW- 목표
- verify pkg:golang/golang.org/x/sync@v0.22.0
- 심벌
-
- errgroup.WithContext
- errgroup.Group.SetLimit
- semaphore.NewWeighted
- singleflight.Group
- 생성일
- 2026-08-20T20:40:28Z
컨트랙트
- errgroup.WithContext cancels derived context and returns error on first subtask failure
- errgroup.Group with SetLimit limits maximum concurrent task executions
- semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release
- singleflight.Group deduplicates concurrent executions for identical keys
파일
- PROMPT.md
- contract_test.go
- csx.json
- go.mod
- go.sum
- spec.json
- sync_sample.go
소스
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify pkg:golang/golang.org/x/sync@v0.22.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/golang.org/x/sync@v0.22.0
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
package sample
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
func TestErrgroupWithContextCancellation(t *testing.T) {
ctx := context.Background()
expectedErr := errors.New("subtask failure")
var canceledObserved int32
tasks := []func(ctx context.Context) error{
func(ctx context.Context) error {
time.Sleep(20 * time.Millisecond)
return expectedErr
},
func(ctx context.Context) error {
select {
case <-ctx.Done():
atomic.StoreInt32(&canceledObserved, 1)
return ctx.Err()
case <-time.After(500 * time.Millisecond):
return nil
}
},
}
err := RunTaskGroup(ctx, tasks)
if !errors.Is(err, expectedErr) && (err == nil || err.Error() != expectedErr.Error()) {
t.Fatalf("expected error %v, got %v", expectedErr, err)
}
if atomic.LoadInt32(&canceledObserved) != 1 {
t.Fatal("expected derived context to be canceled on subtask failure")
}
// Direct verification with errgroup.WithContext
g, gCtx := errgroup.WithContext(context.Background())
g.Go(func() error {
return errors.New("direct fail")
})
if err := g.Wait(); err == nil {
t.Fatal("expected error from direct errgroup.WithContext")
}
if gCtx.Err() == nil {
t.Fatal("expected direct group context to be canceled")
}
}
func TestErrgroupSetLimitConcurrency(t *testing.T) {
limit := 2
totalTasks := 8
var tc TrackConcurrency
tasks := make([]func() error, totalTasks)
for i := 0; i < totalTasks; i++ {
tasks[i] = func() error {
tc.Enter()
defer tc.Leave()
time.Sleep(20 * time.Millisecond)
return nil
}
}
if err := RunBoundedTasks(limit, tasks); err != nil {
t.Fatalf("RunBoundedTasks failed: %v", err)
}
peak := tc.Peak()
if peak > int64(limit) {
t.Fatalf("expected peak concurrency <= %d, observed %d", limit, peak)
}
if peak < 2 {
t.Fatalf("expected peak concurrency to reach %d, observed %d", limit, peak)
}
// Direct verification of errgroup.Group SetLimit
var directGroup errgroup.Group
directGroup.SetLimit(1)
var directExecs int32
directGroup.Go(func() error {
atomic.AddInt32(&directExecs, 1)
return nil
})
if err := directGroup.Wait(); err != nil {
t.Fatalf("directGroup failed: %v", err)
}
if atomic.LoadInt32(&directExecs) != 1 {
t.Fatal("expected directGroup to execute task")
}
}
func TestSemaphoreWeightedAccess(t *testing.T) {
mgr := NewResourceManager(2)
// TryAcquire max tokens
if !mgr.TryAcquire(2) {
t.Fatal("expected TryAcquire(2) to succeed on fresh semaphore")
}
// TryAcquire should fail when no tokens are available
if mgr.TryAcquire(1) {
t.Fatal("expected TryAcquire(1) to fail when capacity is exhausted")
}
// Release 2 tokens
mgr.Release(2)
// Acquire 1 token with context
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := mgr.Acquire(ctx, 1); err != nil {
t.Fatalf("expected Acquire(1) to succeed: %v", err)
}
// TryAcquire remaining 1 token
if !mgr.TryAcquire(1) {
t.Fatal("expected TryAcquire(1) to succeed for remaining capacity")
}
// Release both tokens
mgr.Release(2)
// Direct semaphore.NewWeighted verification
sem := semaphore.NewWeighted(1)
if !sem.TryAcquire(1) {
t.Fatal("expected semaphore.NewWeighted TryAcquire(1) to succeed")
}
sem.Release(1)
}
func TestSingleflightDeduplication(t *testing.T) {
var fetcher CachedFetcher
var calls int32
concurrentCallers := 5
var wg sync.WaitGroup
results := make([]string, concurrentCallers)
sharedResults := make([]bool, concurrentCallers)
errs := make([]error, concurrentCallers)
for i := 0; i < concurrentCallers; i++ {
wg.Add(1)
idx := i
go func() {
defer wg.Done()
res, err, shared := fetcher.Fetch("resource-key", func() (string, error) {
atomic.AddInt32(&calls, 1)
time.Sleep(50 * time.Millisecond)
return "computed-data", nil
})
results[idx] = res
sharedResults[idx] = shared
errs[idx] = err
}()
}
wg.Wait()
for i := 0; i < concurrentCallers; i++ {
if errs[i] != nil {
t.Fatalf("caller %d got error: %v", i, errs[i])
}
if results[i] != "computed-data" {
t.Fatalf("caller %d got unexpected result: %s", i, results[i])
}
}
totalCalls := atomic.LoadInt32(&calls)
if totalCalls != 1 {
t.Fatalf("expected underlying fetch function to be called exactly once, called %d times", totalCalls)
}
// Direct singleflight.Group verification
var directGroup singleflight.Group
val, err, _ := directGroup.Do("test-direct", func() (interface{}, error) {
return "ok", nil
})
if err != nil || val != "ok" {
t.Fatalf("expected direct singleflight to return ok, got %v, err=%v", val, err)
}
}
{"case":{"caseId":"case:sha256:aa8fc042bc449ea2f5a7ae628f2002259513cbf0d0c484e1728b23e9089f533c","contract":["errgroup.WithContext cancels derived context and returns error on first subtask failure","errgroup.Group with SetLimit limits maximum concurrent task executions","semaphore.NewWeighted manages weighted access with TryAcquire, Acquire, and Release","singleflight.Group deduplicates concurrent executions for identical keys"],"goal":"verify pkg:golang/golang.org/x/sync@v0.22.0","kind":"HOW","packages":["pkg:golang/golang.org/x/sync@v0.22.0"],"schemaVersion":1,"symbols":["errgroup.WithContext","errgroup.Group.SetLimit","semaphore.NewWeighted","singleflight.Group"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/sync@v0.22.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/sync@v0.22.0","symbols":["errgroup.WithContext","errgroup.Group.SetLimit","semaphore.NewWeighted","singleflight.Group"],"verifierAdapter":"golang@1"}
module sample
go 1.26.6
require golang.org/x/sync v0.22.0
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
{
"schemaVersion": 1,
"goal": "verify pkg:golang/golang.org/x/sync@v0.22.0",
"kind": "HOW",
"packages": [
"pkg:golang/golang.org/x/sync@v0.22.0"
]
}
package sample
import (
"context"
"errors"
"fmt"
"sync/atomic"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
// RunTaskGroup executes tasks concurrently, canceling all tasks on first failure.
func RunTaskGroup(ctx context.Context, tasks []func(ctx context.Context) error) error {
g, groupCtx := errgroup.WithContext(ctx)
for _, task := range tasks {
t := task
g.Go(func() error {
return t(groupCtx)
})
}
return g.Wait()
}
// RunBoundedTasks executes tasks with bounded concurrency.
func RunBoundedTasks(limit int, tasks []func() error) error {
if limit <= 0 {
return errors.New("limit must be greater than 0")
}
var g errgroup.Group
g.SetLimit(limit)
for _, task := range tasks {
t := task
g.Go(func() error {
return t()
})
}
return g.Wait()
}
// ResourceManager manages resource concurrency using a weighted semaphore.
type ResourceManager struct {
sem *semaphore.Weighted
}
// NewResourceManager creates a manager with max tokens.
func NewResourceManager(tokens int64) *ResourceManager {
return &ResourceManager{
sem: semaphore.NewWeighted(tokens),
}
}
// TryAcquire attempts to acquire n tokens without blocking.
func (r *ResourceManager) TryAcquire(n int64) bool {
return r.sem.TryAcquire(n)
}
// Acquire acquires n tokens with context.
func (r *ResourceManager) Acquire(ctx context.Context, n int64) error {
return r.sem.Acquire(ctx, n)
}
// Release releases n tokens.
func (r *ResourceManager) Release(n int64) {
r.sem.Release(n)
}
// CachedFetcher deduplicates concurrent fetch calls using singleflight.
type CachedFetcher struct {
group singleflight.Group
}
// Fetch executes fn deduplicated by key.
func (c *CachedFetcher) Fetch(key string, fn func() (string, error)) (string, error, bool) {
v, err, shared := c.group.Do(key, func() (interface{}, error) {
res, err := fn()
if err != nil {
return nil, err
}
return res, nil
})
if err != nil {
return "", err, shared
}
resStr, ok := v.(string)
if !ok {
return "", fmt.Errorf("unexpected value type %T", v), shared
}
return resStr, nil, shared
}
// TrackConcurrency tracks active workers and maximum observed concurrency.
type TrackConcurrency struct {
current int64
peak int64
}
// Enter records a worker starting.
func (tc *TrackConcurrency) Enter() {
cur := atomic.AddInt64(&tc.current, 1)
for {
peak := atomic.LoadInt64(&tc.peak)
if cur <= peak || atomic.CompareAndSwapInt64(&tc.peak, peak, cur) {
break
}
}
}
// Leave records a worker finishing.
func (tc *TrackConcurrency) Leave() {
atomic.AddInt64(&tc.current, -1)
}
// Peak returns the maximum concurrent workers observed.
func (tc *TrackConcurrency) Peak() int64 {
return atomic.LoadInt64(&tc.peak)
}
오리진 시더
익명