Skip to content

Commit 221c28a

Browse files
committed
auto merge of rust-lang#15781 : alexcrichton/rust/issue-15758, r=bblum
Semaphores are not currently designed to handle this case correctly, leading to very strange behavior. Semaphores as written are intended to count *resources* and it's not possible to have a negative number of resources. This alters the behavior and documentation to note that the task will be failed if the initial count is 0. Closes rust-lang#15758
2 parents 2224edc + 3419e20 commit 221c28a

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/libsync/raw.rs

+11
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ struct SemGuard<'a, Q> {
109109

110110
impl<Q: Send> Sem<Q> {
111111
fn new(count: int, q: Q) -> Sem<Q> {
112+
assert!(count >= 0,
113+
"semaphores cannot be initialized with negative values");
112114
Sem {
113115
lock: mutex::Mutex::new(),
114116
inner: Unsafe::new(SemInner {
@@ -364,6 +366,10 @@ pub struct SemaphoreGuard<'a> {
364366

365367
impl Semaphore {
366368
/// Create a new semaphore with the specified count.
369+
///
370+
/// # Failure
371+
///
372+
/// This function will fail if `count` is negative.
367373
pub fn new(count: int) -> Semaphore {
368374
Semaphore { sem: Sem::new(count, ()) }
369375
}
@@ -637,6 +643,11 @@ mod tests {
637643
let _g = s.access();
638644
}
639645
#[test]
646+
#[should_fail]
647+
fn test_sem_basic2() {
648+
Semaphore::new(-1);
649+
}
650+
#[test]
640651
fn test_sem_as_mutex() {
641652
let s = Arc::new(Semaphore::new(1));
642653
let s2 = s.clone();

0 commit comments

Comments
 (0)