Skip to content

Commit

Permalink
Add raw non-RAII APIs for token management
Browse files Browse the repository at this point in the history
Hopefully useful for rust-lang/cargo#6747
  • Loading branch information
alexcrichton committed Mar 14, 2019
1 parent ab123a8 commit c50ba90
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,31 @@ impl Client {
tx: Some(tx),
})
}

/// Blocks the current thread until a token is acquired.
///
/// This is the same as `acquire`, except that it doesn't return an RAII
/// helper. If successful the process will need to guarantee that
/// `release_raw` is called in the future.
pub fn acquire_raw(&self) -> io::Result<()> {
self.inner.acquire()?;
Ok(())
}

/// Releases a jobserver token back to the original jobserver.
///
/// This is intended to be paired with `acquire_raw` if it was called, but
/// in some situations it could also be called to relinquish a process's
/// implicit token temporarily which is then re-acquired later.
pub fn release_raw(&self) -> io::Result<()> {
self.inner.release(None)?;
Ok(())
}
}

impl Drop for Acquired {
fn drop(&mut self) {
drop(self.client.release(&self.data));
drop(self.client.release(Some(&self.data)));
}
}

Expand Down Expand Up @@ -540,12 +560,13 @@ mod imp {
}
}

pub fn release(&self, data: &Acquired) -> io::Result<()> {
pub fn release(&self, data: Option<&Acquired>) -> io::Result<()> {
// Note that the fd may be nonblocking but we're going to go ahead
// and assume that the writes here are always nonblocking (we can
// always quickly release a token). If that turns out to not be the
// case we'll get an error anyway!
match (&self.write).write(&[data.byte])? {
let byte = data.map(|d| d.byte).unwrap_or(b'+');
match (&self.write).write(&[byte])? {
1 => Ok(()),
_ => Err(io::Error::new(io::ErrorKind::Other,
"failed to write token back to jobserver")),
Expand Down Expand Up @@ -849,7 +870,7 @@ mod imp {
}
}

pub fn release(&self, _data: &Acquired) -> io::Result<()> {
pub fn release(&self, _data: Option<&Acquired>) -> io::Result<()> {
unsafe {
let r = ReleaseSemaphore(self.sem.0, 1, ptr::null_mut());
if r != 0 {
Expand Down
10 changes: 10 additions & 0 deletions tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,16 @@ const TESTS: &[Test] = &[
assert!(hit.load(Ordering::SeqCst));
},
},
Test {
name: "acquire_raw",
make_args: &["-j2"],
rule: &|me| format!("+{}", me),
f: &|| {
let c = unsafe { Client::from_env().unwrap() };
c.acquire_raw().unwrap();
c.release_raw().unwrap();
},
},
];

fn main() {
Expand Down

0 comments on commit c50ba90

Please sign in to comment.