1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Generic support for building blocking abstractions.
13 use thread
::{self, Thread}
;
14 use sync
::atomic
::{AtomicBool, Ordering}
;
24 unsafe impl Send
for Inner {}
25 unsafe impl Sync
for Inner {}
28 pub struct SignalToken
{
32 pub struct WaitToken
{
36 impl !Send
for WaitToken {}
38 impl !Sync
for WaitToken {}
40 pub fn tokens() -> (WaitToken
, SignalToken
) {
41 let inner
= Arc
::new(Inner
{
42 thread
: thread
::current(),
43 woken
: AtomicBool
::new(false),
45 let wait_token
= WaitToken
{
48 let signal_token
= SignalToken
{
51 (wait_token
, signal_token
)
55 pub fn signal(&self) -> bool
{
56 let wake
= !self.inner
.woken
.compare_and_swap(false, true, Ordering
::SeqCst
);
58 self.inner
.thread
.unpark();
63 /// Convert to an unsafe usize value. Useful for storing in a pipe's state
66 pub unsafe fn cast_to_usize(self) -> usize {
67 mem
::transmute(self.inner
)
70 /// Convert from an unsafe usize value. Useful for retrieving a pipe's state
73 pub unsafe fn cast_from_usize(signal_ptr
: usize) -> SignalToken
{
74 SignalToken { inner: mem::transmute(signal_ptr) }
80 while !self.inner
.woken
.load(Ordering
::SeqCst
) {
85 /// Returns true if we wake up normally, false otherwise.
86 pub fn wait_max_until(self, end
: Instant
) -> bool
{
87 while !self.inner
.woken
.load(Ordering
::SeqCst
) {
88 let now
= Instant
::now();
92 thread
::park_timeout(end
- now
)