# perldoc > Thread::Semaphore

---
type: CommandReference
command: Thread::Semaphore
mode: perldoc
section: 
source: perldoc
---

## Quick Reference

- `my $s = Thread::Semaphore->new($n)` — Create semaphore with initial count $n (default 1)
- `$s->down($n)` — Decrement by $n (block if insufficient count; $n defaults to 1)
- `$s->up($n)` — Increment by $n (unblock waiting threads; $n defaults to 1)
- `$s->down_nb($n)` — Non-blocking decrement; returns true if succeeded
- `$s->down_force($n)` — Force decrement even if count goes negative
- `$s->down_timed($timeout, $n)` — Decrement with timeout; returns false on timeout

## Name

Thread::Semaphore - Thread-safe semaphores

## Synopsis

perl
use Thread::Semaphore;
my $s = Thread::Semaphore->new();
$s->down();   # P operation (block if count <= 0)
# guarded section
$s->up();     # V operation

my $s = Thread::Semaphore->new($initial_value);
$s->down($down_value);
$s->up($up_value);
if ($s->down_nb($down_value)) {
    # guarded section
    $s->up($up_value);
}
$s->down_force($down_value);
$s->down_timed($timeout, $down_value);
Thread::Semaphore works in both threaded and non-threaded applications.

## Options

- `new(NUMBER)` — Create a new semaphore with initial count (default 1). Must be an integer.
- `down(NUMBER)` — Decrease count by NUMBER (default 1). Blocks if count would drop below zero. (Semaphore P operation)
- `up(NUMBER)` — Increase count by NUMBER (default 1). Unblocks any thread blocked trying to `down` if the new count is sufficient. (Semaphore V operation)
- `down_nb(NUMBER)` — Attempt to decrease count by NUMBER (default 1). Returns false if count would drop below zero; does not block.
- `down_force(NUMBER)` — Decrease count by NUMBER (default 1) even if count goes below zero. Does not block.
- `down_timed(TIMEOUT, NUMBER)` — Attempt to decrease count by NUMBER (default 1) within TIMEOUT seconds. Blocks until count is sufficient or timeout. Returns false on timeout.

## Examples

perl
use Thread::Semaphore;
my $s = Thread::Semaphore->new();
$s->down();   # P operation
# guarded section
$s->up();     # V operation

my $s = Thread::Semaphore->new(3);
$s->down(2);  # reserve 2 units
# guarded section
$s->up(2);    # release 2 units

if ($s->down_nb()) {
    # guarded section
    $s->up();
}

$s->down_force();  # force decrement even if count is 0
$s->down_timed(5); # try to decrement within 5 seconds
## See Also

- [Thread::Semaphore on MetaCPAN](https://metacpan.org/release/Thread-Semaphore)
- Code repository: [GitHub](https://github.com/Dual-Life/Thread-Semaphore)
- [threads](https://perldoc.perl.org/threads)
- [threads::shared](https://perldoc.perl.org/threads::shared)
- Sample code in the *examples* directory of the distribution on CPAN