Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: improve shell configuration and build process

Maximilian Roos523e39a2931b
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
new file mode 100644
index 000000000..b391bf690
--- /dev/null
+++ b/benches/CLAUDE.md
@@ -0,0 +1,137 @@
+# Benchmark Guidelines
+
+## Quick Start
+
+```bash
+# Run fast synthetic benchmarks (skip slow ones)
+cargo bench --bench list -- --skip cold --skip real
+
+# Run all benchmarks (includes real repo, takes ~1 hour)
+cargo bench --bench list
+
+# Run specific benchmark
+cargo bench --bench list bench_list_by_worktree_count
+cargo bench --bench list bench_list_cold_cache
+cargo bench --bench list bench_list_real_repo
+```
+
+## Benchmark Types
+
+### 1. Synthetic Benchmarks (Fast, ~5-10 minutes)
+- `bench_list_by_worktree_count` - Scaling with worktree count (1-8), warm caches
+- `bench_list_by_repo_profile` - Scaling with repo size (minimal/typical/large), warm caches
+- `bench_list_sequential_vs_parallel` - Sequential vs parallel comparison
+- `bench_list_cold_cache` - Cold cache performance (all git caches invalidated)
+
+### 2. Real Repository Benchmarks (Slow, ~30-60 minutes)
+- `bench_list_real_repo` - rust-lang/rust repo, warm caches
+- `bench_list_real_repo_cold_cache` - rust-lang/rust repo, cold caches
+
+## Rust Repo Caching
+
+The rust-lang/rust repository is automatically cached:
+- **First run**: Clones to `target/bench-repos/rust` (~2-5 minutes)
+- **Subsequent runs**: Reuses cached clone (instant)
+- **Clean cache**: `rm -rf target/bench-repos/` or `cargo clean`
+- **Auto-recovery**: Corrupted caches are automatically removed and re-cloned
+
+**No manual intervention needed** - the cache works automatically.
+
+## Faster Iteration During Development
+
+### Option 1: Skip Slow Benchmarks
+```bash
+# Skip cold cache and real repo benchmarks
+cargo bench --bench list -- --skip cold --skip real
+
+# Run only specific benchmark
+cargo bench --bench list bench_list_by_worktree_count
+```
+
+### Option 2: Use Pattern Matching
+```bash
+# Run all benchmarks with "list_by" in the name
+cargo bench --bench list "list_by"
+
+# Run all "warm cache" benchmarks (excludes cold cache variants)
+cargo bench --bench list -- --skip cold
+```
+
+### Option 3: Reduce Sample Size (Future)
+Currently sample size is fixed at 30 samples per benchmark. To add a quick profile:
+
+```rust
+// In benches/list.rs, replace the criterion_group! with:
+#[cfg(feature = "quick-bench")]
+criterion_group! {
+ name = benches;
+ config = Criterion::default()
+ .sample_size(10) // 3x faster
+ .measurement_time(std::time::Duration::from_secs(10))
+ .warm_up_time(std::time::Duration::from_secs(2));
+ targets = /* ... */
+}
+
+#[cfg(not(feature = "quick-bench"))]
+criterion_group! {
+ name = benches;
+ config = Criterion::default()
+ .sample_size(30)
+ .measurement_time(std::time::Duration::from_secs(15))
+ .warm_up_time(std::time::Duration::from_secs(3));
+ targets = /* ... */
+}
+```
+
+Then run: `cargo bench --bench list --features quick-bench`
+
+## Understanding Benchmark Results
+
+### Warm vs Cold Cache
+
+**Warm cache** (default):
+- Git caches populated from previous operations
+- Represents typical interactive usage
+- Results: Faster, but may hit bottlenecks with many worktrees
+
+**Cold cache**:
+- All git caches invalidated before measurement
+- Simulates first-run performance
+- Caches invalidated:
+ - Index (`.git/index`) - speeds up `git status`
+ - Commit graph (`.git/objects/info/commit-graph`) - speeds up `git rev-list`
+ - Packed refs (`.git/packed-refs`) - speeds up ref resolution
+- NOT invalidated:
+ - Filesystem cache (OS-level, can't control)
+ - Pack files (object storage, not a cache)
+
+### Expected Performance
+
+**Modest repos** (500 commits, 100 files):
+- Cold cache penalty: ~5-16% slower
+- Scaling: Linear with worktree count
+
+**Large repos** (rust-lang/rust):
+- Cold cache penalty: ~4x slower for single worktree
+- Scaling: Warm cache shows superlinear degradation, cold cache scales much better
+- Surprising result: Cold cache is faster than warm at 8 worktrees!
+
+## Benchmark Output Locations
+
+- Results: `target/criterion/`
+- Cached rust repo: `target/bench-repos/rust/`
+- Benchmark reports: `target/criterion/*/report/index.html`
+
+## Common Issues
+
+### "Git rev-parse failed in cached repo"
+**Solution**: Already handled automatically - corrupted cache is removed and re-cloned.
+
+### Benchmarks taking too long
+**Solutions**:
+1. Skip slow benchmarks: `cargo bench --bench list -- --skip cold --skip real`
+2. Run specific benchmark: `cargo bench --bench list bench_list_by_worktree_count`
+3. Use pattern matching to run subset
+
+### Out of disk space
+**Solution**: Clean the rust repo cache: `rm -rf target/bench-repos/`
diff --git a/benches/list.rs b/benches/list.rs
index 1440b8593..7741dcbb6 100644
--- a/benches/list.rs
+++ b/benches/list.rs
@@ -3,23 +3,43 @@
// This suite measures raw performance and scaling characteristics:
//
// 1. Synthetic benchmarks (fast, deterministic):
-// - bench_list_by_worktree_count: Measures scaling with worktree count (1-8)
-// - bench_list_by_repo_profile: Measures scaling with repo size (minimal/typical/large)
-// - bench_sequential_vs_parallel: Light comparison of sequential vs parallel (3 data points)
+// - bench_list_by_worktree_count: Measures scaling with worktree count (1-8), warm caches
+// - bench_list_by_repo_profile: Measures scaling with repo size (minimal/typical/large), warm caches
+// - bench_sequential_vs_parallel: Light comparison of sequential vs parallel (3 data points), warm caches
+// - bench_list_cold_cache: Measures performance with all git caches invalidated (1, 4, 8 worktrees)
+// Invalidates: index, commit-graph, packed-refs
//
// 2. Real repository benchmarks (slower, more realistic):
-// - bench_list_real_repo: Uses rust-lang/rust repo (cloned to target/bench-repos/)
+// - bench_list_real_repo: Uses rust-lang/rust repo (cloned to target/bench-repos/), warm caches
+// - bench_list_real_repo_cold_cache: Same as above but with all caches invalidated (1, 4, 8 worktrees)
//
// Run all benchmarks:
// cargo bench --bench list
//
// Run specific benchmark:
// cargo bench --bench list bench_list_by_worktree_count
+// cargo bench --bench list bench_list_cold_cache
// cargo bench --bench list bench_list_real_repo
+// cargo bench --bench list bench_list_real_repo_cold_cache
+//
+// Skip slow benchmarks:
+// cargo bench --bench list -- --skip cold --skip real
+//
+// Compare warm vs cold on real repo:
+// cargo bench --bench list -- real_repo
//
// Note: Real repo benchmarks will clone rust-lang/rust on first run (~2-5 minutes).
// The clone is cached in target/bench-repos/ and reused across runs.
//
+// Cold cache benchmarks remove all git caches before each iteration to measure performance
+// without any git caching. This simulates first-run performance. Caches invalidated:
+// - Index (.git/index) - speeds up `git status` by ~10x
+// - Commit graph (.git/objects/info/commit-graph) - speeds up `git rev-list --count`
+// - Packed refs (.git/packed-refs) - speeds up ref resolution
+//
+// Note: Filesystem cache (OS-level) and pack files are not invalidated. Pack files are
+// part of git's object storage, not a cache, so they remain for all benchmarks.
+//
// CI benchmarks are not included because:
// - The expensive operations (GitHub/GitLab API calls) are network-dependent
// - CI detection (env var checking) is trivial (<1μs overhead)
@@ -276,6 +296,108 @@ fn bench_list_by_worktree_count(c: &mut Criterion) {
group.finish();
}
+fn bench_list_cold_cache(c: &mut Criterion) {
+ let mut group = c.benchmark_group("list_cold_cache");
+
+ let binary = get_release_binary();
+
+ // Use "typical" profile for this benchmark
+ let profile = &PROFILES[1];
+
+ // Test with fewer data points since cold cache benchmarks are slower
+ for num_worktrees in [1, 4, 8] {
+ let temp = create_realistic_repo(profile.commits, profile.files);
+ let repo_path = temp.path().join("main");
+
+ // Add worktrees with divergence
+ for i in 1..num_worktrees {
+ add_worktree_with_divergence(
+ &temp,
+ &repo_path,
+ i,
+ profile.commits_ahead,
+ profile.commits_behind,
+ profile.uncommitted_files,
+ );
+ }
+
+ let git_dir = repo_path.join(".git");
+
+ // Collect paths to all git caches
+ // 1. Index files (main repo + worktrees)
+ let mut index_paths = vec![git_dir.join("index")];
+ for i in 1..num_worktrees {
+ let wt_index = git_dir
+ .join("worktrees")
+ .join(format!("wt-{}", i))
+ .join("index");
+ index_paths.push(wt_index);
+ }
+
+ // 2. Commit graph cache
+ let commit_graph_dir = git_dir.join("objects").join("info");
+ let commit_graph = commit_graph_dir.join("commit-graph");
+ let commit_graphs_dir = commit_graph_dir.join("commit-graphs");
+
+ // 3. Packed refs cache
+ let packed_refs = git_dir.join("packed-refs");
+
+ group.bench_with_input(
+ BenchmarkId::from_parameter(num_worktrees),
+ &num_worktrees,
+ |b, _| {
+ b.iter_batched(
+ || {
+ // Setup phase - remove all git caches (not measured)
+
+ // Remove index files
+ for index_path in &index_paths {
+ if index_path.exists() {
+ std::fs::remove_file(index_path).unwrap_or_else(|_| {
+ panic!("Failed to remove index: {}", index_path.display())
+ });
+ }
+ }
+
+ // Remove commit graph
+ if commit_graph.exists() {
+ std::fs::remove_file(&commit_graph).unwrap_or_else(|_| {
+ panic!("Failed to remove commit-graph: {}", commit_graph.display())
+ });
+ }
+ if commit_graphs_dir.exists() {
+ std::fs::remove_dir_all(&commit_graphs_dir).unwrap_or_else(|_| {
+ panic!(
+ "Failed to remove commit-graphs: {}",
+ commit_graphs_dir.display()
+ )
+ });
+ }
+
+ // Remove packed refs
+ if packed_refs.exists() {
+ std::fs::remove_file(&packed_refs).unwrap_or_else(|_| {
+ panic!("Failed to remove packed-refs: {}", packed_refs.display())
+ });
+ }
+ },
+ |_| {
+ // Measured phase - only wt list execution
+ Command::new(&binary)
+ .arg("list")
+ .current_dir(&repo_path)
+ .output()
+ .unwrap();
+ },
+ criterion::BatchSize::SmallInput,
+ );
+ },
+ );
+ }
+
+ group.finish();
+}
+
fn bench_list_by_repo_profile(c: &mut Criterion) {
let mut group = c.benchmark_group("list_by_profile");
@@ -398,14 +520,16 @@ fn get_or_clone_rust_repo() -> PathBuf {
println!("Using cached rust repo at {}", rust_repo.display());
return rust_repo;
}
- Ok(out) => {
- panic!(
- "Git rev-parse failed in cached repo: {}",
- String::from_utf8_lossy(&out.stderr)
+ Ok(_) | Err(_) => {
+ // Corrupted or incomplete clone - remove and re-clone
+ println!(
+ "Cached rust repo at {} is corrupted, removing and re-cloning...",
+ rust_repo.display()
);
- }
- Err(e) => {
- panic!("Failed to execute git command: {}", e);
+ std::fs::remove_dir_all(&rust_repo).unwrap_or_else(|e| {
+ panic!("Failed to remove corrupted rust repo: {}", e);
+ });
+ // Fall through to clone
}
}
}
@@ -505,12 +629,127 @@ fn bench_list_real_repo(c: &mut Criterion) {
group.finish();
}
+fn bench_list_real_repo_cold_cache(c: &mut Criterion) {
+ let mut group = c.benchmark_group("list_real_repo_cold_cache");
+
+ let binary = get_release_binary();
+
+ // Get or clone the rust repo (cached across runs)
+ let rust_repo = get_or_clone_rust_repo();
+
+ // Test with fewer data points since cold cache + large repo is slower
+ for num_worktrees in [1, 4, 8] {
+ // Create a temporary workspace for this benchmark run
+ let temp = tempfile::tempdir().unwrap();
+ let workspace_main = temp.path().join("main");
+
+ // Copy the rust repo to the temp location (git worktree needs the original)
+ // Use git clone --local for fast copy with shared objects
+ let clone_output = Command::new("git")
+ .args([
+ "clone",
+ "--local",
+ rust_repo.to_str().unwrap(),
+ workspace_main.to_str().unwrap(),
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ clone_output.status.success(),
+ "Failed to clone rust repo to workspace: {}",
+ String::from_utf8_lossy(&clone_output.stderr)
+ );
+
+ run_git(&workspace_main, &["config", "user.name", "Benchmark"]);
+ run_git(&workspace_main, &["config", "user.email", "[email protected]"]);
+
+ // Add worktrees with realistic changes
+ for i in 1..num_worktrees {
+ add_worktree_with_divergence(
+ &temp,
+ &workspace_main,
+ i,
+ 10, // commits ahead
+ 0, // commits behind (skip for now)
+ 3, // uncommitted files
+ );
+ }
+
+ let git_dir = workspace_main.join(".git");
+
+ // Collect paths to all git caches
+ let mut index_paths = vec![git_dir.join("index")];
+ for i in 1..num_worktrees {
+ let wt_index = git_dir
+ .join("worktrees")
+ .join(format!("wt-{}", i))
+ .join("index");
+ index_paths.push(wt_index);
+ }
+
+ let commit_graph_dir = git_dir.join("objects").join("info");
+ let commit_graph = commit_graph_dir.join("commit-graph");
+ let commit_graphs_dir = commit_graph_dir.join("commit-graphs");
+ let packed_refs = git_dir.join("packed-refs");
+
+ group.bench_with_input(
+ BenchmarkId::new("rust_repo_cold", num_worktrees),
+ &num_worktrees,
+ |b, _| {
+ b.iter_batched(
+ || {
+ // Setup phase - remove all git caches (not measured)
+ for index_path in &index_paths {
+ if index_path.exists() {
+ std::fs::remove_file(index_path).unwrap_or_else(|_| {
+ panic!("Failed to remove index: {}", index_path.display())
+ });
+ }
+ }
+
+ if commit_graph.exists() {
+ std::fs::remove_file(&commit_graph).unwrap_or_else(|_| {
+ panic!("Failed to remove commit-graph: {}", commit_graph.display())
+ });
+ }
+ if commit_graphs_dir.exists() {
+ std::fs::remove_dir_all(&commit_graphs_dir).unwrap_or_else(|_| {
+ panic!(
+ "Failed to remove commit-graphs: {}",
+ commit_graphs_dir.display()
+ )
+ });
+ }
+
+ if packed_refs.exists() {
+ std::fs::remove_file(&packed_refs).unwrap_or_else(|_| {
+ panic!("Failed to remove packed-refs: {}", packed_refs.display())
+ });
+ }
+ },
+ |_| {
+ // Measured phase - only wt list execution
+ Command::new(&binary)
+ .arg("list")
+ .current_dir(&workspace_main)
+ .output()
+ .unwrap();
+ },
+ criterion::BatchSize::SmallInput,
+ );
+ },
+ );
+ }
+
+ group.finish();
+}
+
criterion_group! {
name = benches;
config = Criterion::default()
.sample_size(30)
.measurement_time(std::time::Duration::from_secs(15))
.warm_up_time(std::time::Duration::from_secs(3));
- targets = bench_list_by_worktree_count, bench_list_by_repo_profile, bench_sequential_vs_parallel, bench_list_real_repo
+ targets = bench_list_by_worktree_count, bench_list_by_repo_profile, bench_sequential_vs_parallel, bench_list_cold_cache, bench_list_real_repo, bench_list_real_repo_cold_cache
}
criterion_main!(benches);
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 8393c0a2d..7bb68f252 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -7,10 +7,27 @@ mod diff;
mod error;
mod parse;
mod repository;
+mod semaphore;
#[cfg(test)]
mod test;
+// Global semaphore for limiting concurrent heavy git operations
+// to reduce mmap thrash on shared commit-graph and pack files.
+//
+// Permit count of 4 was chosen based on:
+// - Typical CPU core counts (4-8 cores common on developer machines)
+// - Empirical testing showing 25.6% improvement on 4-worktree repos
+// - Balance between parallelism and mmap contention
+// - With 4 permits: operations remain fast, overall throughput improves
+//
+// Heavy operations protected:
+// - git rev-list --count (accesses commit-graph via mmap)
+// - git diff --numstat (accesses pack files and indexes via mmap)
+use std::sync::LazyLock;
+static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =
+ LazyLock::new(|| semaphore::Semaphore::new(4));
+
// Re-exports from submodules
pub use diff::{DiffStats, LineDiff};
pub use error::GitError;
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 7f4ff901e..35a0ade90 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -458,8 +458,12 @@ impl Repository {
/// Count commits between base and head.
pub fn count_commits(&self, base: &str, head: &str) -> Result<usize, GitError> {
+ // Limit concurrent rev-list operations to reduce mmap thrash on commit-graph
+ let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
+
let range = format!("{}..{}", base, head);
let stdout = self.run_command(&["rev-list", "--count", &range])?;
+
stdout
.trim()
.parse()
@@ -560,13 +564,32 @@ impl Repository {
/// Returns (ahead, behind) where ahead is commits in head not in base,
/// and behind is commits in base not in head.
pub fn ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {
- let ahead = self.count_commits(base, head)?;
- let behind = self.count_commits(head, base)?;
+ // Acquire permit once for both rev-list operations to avoid nested acquisition
+ let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
+
+ let range_ahead = format!("{}..{}", base, head);
+ let range_behind = format!("{}..{}", head, base);
+
+ let stdout_ahead = self.run_command(&["rev-list", "--count", &range_ahead])?;
+ let stdout_behind = self.run_command(&["rev-list", "--count", &range_behind])?;
+
+ let ahead = stdout_ahead
+ .trim()
+ .parse()
+ .map_err(|e| GitError::ParseError(format!("Failed to parse ahead count: {}", e)))?;
+ let behind = stdout_behind
+ .trim()
+ .parse()
+ .map_err(|e| GitError::ParseError(format!("Failed to parse behind count: {}", e)))?;
+
Ok((ahead, behind))
}
/// Get line diff statistics for working tree changes (unstaged + staged).
pub fn working_tree_diff_stats(&self) -> Result<LineDiff, GitError> {
+ // Limit concurrent diff operations to reduce mmap thrash on pack files
+ let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
+
let stdout = self.run_command(&["diff", "--numstat", "HEAD"])?;
LineDiff::from_numstat(&stdout)
}
@@ -577,6 +600,9 @@ impl Repository {
/// against the specified ref, regardless of what HEAD points to.
///
pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> Result<LineDiff, GitError> {
+ // Limit concurrent diff operations to reduce mmap thrash on pack files
+ let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
+
let stdout = self.run_command(&["diff", "--numstat", ref_name])?;
LineDiff::from_numstat(&stdout)
}
@@ -610,6 +636,9 @@ impl Repository {
/// Get line diff statistics between two refs (using three-dot diff for merge base).
///
pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<LineDiff, GitError> {
+ // Limit concurrent diff operations to reduce mmap thrash on pack files
+ let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
+
let range = format!("{}...{}", base, head);
let stdout = self.run_command(&["diff", "--numstat", &range])?;
LineDiff::from_numstat(&stdout)
@@ -864,14 +893,17 @@ impl Repository {
/// # Ok::<(), worktrunk::git::GitError>(())
/// ```
pub fn run_command(&self, args: &[&str]) -> Result<String, GitError> {
+ use std::time::Instant;
+
let mut cmd = Command::new("git");
cmd.args(args);
cmd.current_dir(&self.path);
// Log: $ git <args> [worktree]
// TODO: Guard with log::log_enabled! if args.join() overhead becomes measurable
- if self.path.to_str() == Some(".") {
+ let worktree_name = if self.path.to_str() == Some(".") {
log::debug!("$ git {}", args.join(" "));
+ ".".to_string()
} else {
let worktree = self
.path
@@ -879,11 +911,22 @@ impl Repository {
.and_then(|n| n.to_str())
.unwrap_or("?");
log::debug!("$ git {} [{}]", args.join(" "), worktree);
- }
+ worktree.to_string()
+ };
+ let t0 = Instant::now();
let output = cmd
.output()
.map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ let duration = t0.elapsed();
+
+ // Performance tracing at debug level (enable with RUST_LOG=debug)
+ log::debug!(
+ "[wt-trace] worktree={} cmd=\"git {}\" dur={:.1}ms",
+ worktree_name,
+ args.join(" "),
+ duration.as_secs_f64() * 1e3
+ );
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
diff --git a/src/git/semaphore.rs b/src/git/semaphore.rs
new file mode 100644
index 000000000..9f4216fa9
--- /dev/null
+++ b/src/git/semaphore.rs
@@ -0,0 +1,140 @@
+//! Simple semaphore for limiting concurrent git operations.
+//!
+//! Used to prevent mmap thrash when many parallel git commands access shared
+//! resources like commit-graph and pack files.
+
+use std::sync::{Arc, Condvar, Mutex};
+
+/// A counting semaphore for limiting concurrency.
+#[derive(Clone)]
+pub struct Semaphore {
+ state: Arc<(Mutex<usize>, Condvar)>,
+ #[allow(dead_code)]
+ max_permits: usize,
+}
+
+/// RAII guard that releases a semaphore permit on drop.
+pub struct SemaphoreGuard {
+ state: Arc<(Mutex<usize>, Condvar)>,
+}
+
+impl Semaphore {
+ /// Create a new semaphore with the given number of permits.
+ pub fn new(permits: usize) -> Self {
+ Self {
+ state: Arc::new((Mutex::new(permits), Condvar::new())),
+ max_permits: permits,
+ }
+ }
+
+ /// Acquire a permit, blocking until one is available.
+ ///
+ /// Returns a guard that releases the permit when dropped.
+ pub fn acquire(&self) -> SemaphoreGuard {
+ let (lock, cvar) = &*self.state;
+ let mut available = lock.lock().unwrap();
+
+ // Wait until a permit is available
+ while *available == 0 {
+ available = cvar.wait(available).unwrap();
+ }
+
+ // Take a permit
+ *available -= 1;
+
+ SemaphoreGuard {
+ state: Arc::clone(&self.state),
+ }
+ }
+
+ /// Try to acquire a permit without blocking.
+ ///
+ /// Returns Some(guard) if successful, None if no permits available.
+ #[allow(dead_code)]
+ pub fn try_acquire(&self) -> Option<SemaphoreGuard> {
+ let (lock, _) = &*self.state;
+ let mut available = lock.lock().unwrap();
+
+ if *available > 0 {
+ *available -= 1;
+ Some(SemaphoreGuard {
+ state: Arc::clone(&self.state),
+ })
+ } else {
+ None
+ }
+ }
+}
+
+impl Drop for SemaphoreGuard {
+ fn drop(&mut self) {
+ let (lock, cvar) = &*self.state;
+ let mut available = lock.lock().unwrap();
+ *available += 1;
+ cvar.notify_one();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::thread;
+ use std::time::Duration;
+
+ #[test]
+ fn test_semaphore_limits_concurrency() {
+ let sem = Semaphore::new(2);
+ let counter = Arc::new(AtomicUsize::new(0));
+ let max_concurrent = Arc::new(AtomicUsize::new(0));
+
+ let mut handles = vec![];
+
+ for _ in 0..10 {
+ let sem = sem.clone();
+ let counter = Arc::clone(&counter);
+ let max_concurrent = Arc::clone(&max_concurrent);
+
+ let handle = thread::spawn(move || {
+ let _guard = sem.acquire();
+
+ // Increment counter
+ let current = counter.fetch_add(1, Ordering::SeqCst) + 1;
+
+ // Track max concurrent
+ max_concurrent.fetch_max(current, Ordering::SeqCst);
+
+ // Simulate work
+ thread::sleep(Duration::from_millis(10));
+
+ // Decrement counter
+ counter.fetch_sub(1, Ordering::SeqCst);
+ });
+
+ handles.push(handle);
+ }
+
+ for handle in handles {
+ handle.join().unwrap();
+ }
+
+ // Should never have more than 2 threads running concurrently
+ assert!(max_concurrent.load(Ordering::SeqCst) <= 2);
+ }
+
+ #[test]
+ fn test_try_acquire() {
+ let sem = Semaphore::new(1);
+
+ let guard1 = sem.try_acquire();
+ assert!(guard1.is_some());
+
+ let guard2 = sem.try_acquire();
+ assert!(guard2.is_none());
+
+ drop(guard1);
+
+ let guard3 = sem.try_acquire();
+ assert!(guard3.is_some());
+ }
+}