mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-29 00:00:11 +02:00
Fix race condition related bugs (#243)
* Fix races. This mostly pulls in changes from rust-lang-nursery/futures-rs#881, but also updates Registration to be a bit more obvious as to what is going on. * Reduce spurious wakeups caused by Reactor This patch adds an ABA guard on token values before registering them with Mio. This allows catching token reuse and avoid the notification. This is needed for OS X as the notification is used to determine that a TCP connect has completed. A spurious notification can potentially cause write failures.
This commit is contained in:
+48
-32
@@ -5,6 +5,8 @@ extern crate env_logger;
|
|||||||
|
|
||||||
use std::{io, thread};
|
use std::{io, thread};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicUsize;
|
||||||
|
use std::sync::atomic::Ordering::Relaxed;
|
||||||
|
|
||||||
use futures::prelude::*;
|
use futures::prelude::*;
|
||||||
use tokio::net::{TcpStream, TcpListener};
|
use tokio::net::{TcpStream, TcpListener};
|
||||||
@@ -18,7 +20,7 @@ macro_rules! t {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hammer() {
|
fn hammer_old() {
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
|
|
||||||
let threads = (0..10).map(|_| {
|
let threads = (0..10).map(|_| {
|
||||||
@@ -73,48 +75,62 @@ fn hammer_split() {
|
|||||||
use tokio_io::io;
|
use tokio_io::io;
|
||||||
|
|
||||||
const N: usize = 100;
|
const N: usize = 100;
|
||||||
|
const ITER: usize = 100;
|
||||||
|
|
||||||
let _ = env_logger::init();
|
let _ = env_logger::init();
|
||||||
|
|
||||||
let srv = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap()));
|
for _ in 0..ITER {
|
||||||
let addr = t!(srv.local_addr());
|
let srv = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap()));
|
||||||
|
let addr = t!(srv.local_addr());
|
||||||
|
|
||||||
let mut rt = Runtime::new().unwrap();
|
let cnt = Arc::new(AtomicUsize::new(0));
|
||||||
|
|
||||||
fn split(socket: TcpStream) {
|
let mut rt = Runtime::new().unwrap();
|
||||||
let socket = Arc::new(socket);
|
|
||||||
let rd = Rd(socket.clone());
|
|
||||||
let wr = Wr(socket);
|
|
||||||
|
|
||||||
let rd = io::read(rd, vec![0; 1])
|
fn split(socket: TcpStream, cnt: Arc<AtomicUsize>) {
|
||||||
.map(|_| ())
|
let socket = Arc::new(socket);
|
||||||
.map_err(|e| panic!("read error = {:?}", e));
|
let rd = Rd(socket.clone());
|
||||||
|
let wr = Wr(socket);
|
||||||
|
|
||||||
let wr = io::write_all(wr, b"1")
|
let cnt2 = cnt.clone();
|
||||||
.map(|_| ())
|
|
||||||
.map_err(|e| panic!("write error = {:?}", e));
|
|
||||||
|
|
||||||
tokio::spawn(rd);
|
let rd = io::read(rd, vec![0; 1])
|
||||||
tokio::spawn(wr);
|
.map(move |_| {
|
||||||
}
|
cnt2.fetch_add(1, Relaxed);
|
||||||
|
})
|
||||||
|
.map_err(|e| panic!("read error = {:?}", e));
|
||||||
|
|
||||||
rt.spawn({
|
let wr = io::write_all(wr, b"1")
|
||||||
srv.incoming()
|
.map(move |_| {
|
||||||
.map_err(|e| panic!("accept error = {:?}", e))
|
cnt.fetch_add(1, Relaxed);
|
||||||
.take(N as u64)
|
})
|
||||||
.for_each(|socket| {
|
.map_err(move |e| panic!("write error = {:?}", e));
|
||||||
split(socket);
|
|
||||||
Ok(())
|
tokio::spawn(rd);
|
||||||
})
|
tokio::spawn(wr);
|
||||||
});
|
}
|
||||||
|
|
||||||
for _ in 0..N {
|
|
||||||
rt.spawn({
|
rt.spawn({
|
||||||
TcpStream::connect(&addr)
|
let cnt = cnt.clone();
|
||||||
.map_err(|e| panic!("connect error = {:?}", e))
|
srv.incoming()
|
||||||
.map(|socket| split(socket))
|
.map_err(|e| panic!("accept error = {:?}", e))
|
||||||
|
.take(N as u64)
|
||||||
|
.for_each(move |socket| {
|
||||||
|
split(socket, cnt.clone());
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
rt.shutdown_on_idle().wait().unwrap();
|
for _ in 0..N {
|
||||||
|
rt.spawn({
|
||||||
|
let cnt = cnt.clone();
|
||||||
|
TcpStream::connect(&addr)
|
||||||
|
.map_err(move |e| panic!("connect error = {:?}", e))
|
||||||
|
.map(move |socket| split(socket, cnt))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
rt.shutdown_on_idle().wait().unwrap();
|
||||||
|
assert_eq!(N * 4, cnt.load(Relaxed));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use super::Task;
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::cell::UnsafeCell;
|
use std::cell::UnsafeCell;
|
||||||
use std::sync::atomic::AtomicUsize;
|
use std::sync::atomic::AtomicUsize;
|
||||||
use std::sync::atomic::Ordering::{Acquire, Release};
|
use std::sync::atomic::Ordering::{Acquire, Release, AcqRel};
|
||||||
|
|
||||||
use Task;
|
|
||||||
|
|
||||||
/// A synchronization primitive for task notification.
|
/// A synchronization primitive for task notification.
|
||||||
///
|
///
|
||||||
@@ -24,37 +26,115 @@ use Task;
|
|||||||
/// `AtomicTask` does not provide any memory ordering guarantees, as such the
|
/// `AtomicTask` does not provide any memory ordering guarantees, as such the
|
||||||
/// user should use caution and use other synchronization primitives to guard
|
/// user should use caution and use other synchronization primitives to guard
|
||||||
/// the result of the underlying computation.
|
/// the result of the underlying computation.
|
||||||
pub struct AtomicTask {
|
pub(crate) struct AtomicTask {
|
||||||
state: AtomicUsize,
|
state: AtomicUsize,
|
||||||
task: UnsafeCell<Option<Task>>,
|
task: UnsafeCell<Option<Task>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initial state, the `AtomicTask` is currently not being used.
|
// `AtomicTask` is a multi-consumer, single-producer transfer cell. The cell
|
||||||
///
|
// stores a `Task` value produced by calls to `register` and many threads can
|
||||||
/// The value `2` is picked specifically because it between the write lock &
|
// race to take the task (to notify it) by calling `notify.
|
||||||
/// read lock values. Since the read lock is represented by an incrementing
|
//
|
||||||
/// counter, this enables an atomic fetch_sub operation to be used for releasing
|
// If a new `Task` instance is produced by calling `register` before an existing
|
||||||
/// a lock.
|
// one is consumed, then the existing one is overwritten.
|
||||||
const WAITING: usize = 2;
|
//
|
||||||
|
// While `AtomicTask` is single-producer, the implementation ensures memory
|
||||||
|
// safety. In the event of concurrent calls to `register`, there will be a
|
||||||
|
// single winner whose task will get stored in the cell. The losers will not
|
||||||
|
// have their tasks notified. As such, callers should ensure to add
|
||||||
|
// synchronization to calls to `register`.
|
||||||
|
//
|
||||||
|
// The implementation uses a single `AtomicUsize` value to coordinate access to
|
||||||
|
// the `Task` cell. There are two bits that are operated on independently. These
|
||||||
|
// are represented by `REGISTERING` and `NOTIFYING`.
|
||||||
|
//
|
||||||
|
// The `REGISTERING` bit is set when a producer enters the critical section. The
|
||||||
|
// `NOTIFYING` bit is set when a consumer enters the critical section. Neither
|
||||||
|
// bit being set is represented by `WAITING`.
|
||||||
|
//
|
||||||
|
// A thread obtains an exclusive lock on the task cell by transitioning the
|
||||||
|
// state from `WAITING` to `REGISTERING` or `NOTIFYING`, depending on the
|
||||||
|
// operation the thread wishes to perform. When this transition is made, it is
|
||||||
|
// guaranteed that no other thread will access the task cell.
|
||||||
|
//
|
||||||
|
// # Registering
|
||||||
|
//
|
||||||
|
// On a call to `register`, an attempt to transition the state from WAITING to
|
||||||
|
// REGISTERING is made. On success, the caller obtains a lock on the task cell.
|
||||||
|
//
|
||||||
|
// If the lock is obtained, then the thread sets the task cell to the task
|
||||||
|
// provided as an argument. Then it attempts to transition the state back from
|
||||||
|
// `REGISTERING` -> `WAITING`.
|
||||||
|
//
|
||||||
|
// If this transition is successful, then the registering process is complete
|
||||||
|
// and the next call to `notify` will observe the task.
|
||||||
|
//
|
||||||
|
// If the transition fails, then there was a concurrent call to `notify` that
|
||||||
|
// was unable to access the task cell (due to the registering thread holding the
|
||||||
|
// lock). To handle this, the registering thread removes the task it just set
|
||||||
|
// from the cell and calls `notify` on it. This call to notify represents the
|
||||||
|
// attempt to notify by the other thread (that set the `NOTIFYING` bit). The
|
||||||
|
// state is then transitioned from `REGISTERING | NOTIFYING` back to `WAITING`.
|
||||||
|
// This transition must succeed because, at this point, the state cannot be
|
||||||
|
// transitioned by another thread.
|
||||||
|
//
|
||||||
|
// # Notifying
|
||||||
|
//
|
||||||
|
// On a call to `notify`, an attempt to transition the state from `WAITING` to
|
||||||
|
// `NOTIFYING` is made. On success, the caller obtains a lock on the task cell.
|
||||||
|
//
|
||||||
|
// If the lock is obtained, then the thread takes ownership of the current value
|
||||||
|
// in teh task cell, and calls `notify` on it. The state is then transitioned
|
||||||
|
// back to `WAITING`. This transition must succeed as, at this point, the state
|
||||||
|
// cannot be transitioned by another thread.
|
||||||
|
//
|
||||||
|
// If the thread is unable to obtain the lock, the `NOTIFYING` bit is still.
|
||||||
|
// This is because it has either been set by the current thread but the previous
|
||||||
|
// value included the `REGISTERING` bit **or** a concurrent thread is in the
|
||||||
|
// `NOTIFYING` critical section. Either way, no action must be taken.
|
||||||
|
//
|
||||||
|
// If the current thread is the only concurrent call to `notify` and another
|
||||||
|
// thread is in the `register` critical section, when the other thread **exits**
|
||||||
|
// the `register` critical section, it will observe the `NOTIFYING` bit and
|
||||||
|
// handle the notify itself.
|
||||||
|
//
|
||||||
|
// If another thread is in the `notify` critical section, then it will handle
|
||||||
|
// notifying the task.
|
||||||
|
//
|
||||||
|
// # A potential race (is safely handled).
|
||||||
|
//
|
||||||
|
// Imagine the following situation:
|
||||||
|
//
|
||||||
|
// * Thread A obtains the `notify` lock and notifies a task.
|
||||||
|
//
|
||||||
|
// * Before thread A releases the `notify` lock, the notified task is scheduled.
|
||||||
|
//
|
||||||
|
// * Thread B attempts to notify the task. In theory this should result in the
|
||||||
|
// task being notified, but it cannot because thread A still holds the notify
|
||||||
|
// lock.
|
||||||
|
//
|
||||||
|
// This case is handled by requiring users of `AtomicTask` to call `register`
|
||||||
|
// **before** attempting to observe the application state change that resulted
|
||||||
|
// in the task being notified. The notifiers also change the application state
|
||||||
|
// before calling notify.
|
||||||
|
//
|
||||||
|
// Because of this, the task will do one of two things.
|
||||||
|
//
|
||||||
|
// 1) Observe the application state change that Thread B is notifying on. In
|
||||||
|
// this case, it is OK for Thread B's notification to be lost.
|
||||||
|
//
|
||||||
|
// 2) Call register before attempting to observe the application state. Since
|
||||||
|
// Thread A still holds the `notify` lock, the call to `register` will result
|
||||||
|
// in the task notifying itself and get scheduled again.
|
||||||
|
|
||||||
/// The `register` function has determined that the task is no longer current.
|
/// Idle state
|
||||||
/// This implies that `AtomicTask::register` is being called from a different
|
const WAITING: usize = 0;
|
||||||
/// task than is represented by the currently stored task. The write lock is
|
|
||||||
/// obtained to update the task cell.
|
|
||||||
const LOCKED_WRITE: usize = 0;
|
|
||||||
|
|
||||||
/// At least one call to `notify` happened concurrently to `register` updating
|
/// A new task value is being registered with the `AtomicTask` cell.
|
||||||
/// the task cell. This state is detected when `register` exits the mutation
|
const REGISTERING: usize = 0b01;
|
||||||
/// code and signals to `register` that it is responsible for notifying its own
|
|
||||||
/// task.
|
|
||||||
const LOCKED_WRITE_NOTIFIED: usize = 1;
|
|
||||||
|
|
||||||
|
/// The task currently registered with the `AtomicTask` cell is being notified.
|
||||||
/// The `notify` function has locked access to the task cell for notification.
|
const NOTIFYING: usize = 0b10;
|
||||||
///
|
|
||||||
/// The constant is left here mostly for documentation reasons.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
const LOCKED_READ: usize = 3;
|
|
||||||
|
|
||||||
impl AtomicTask {
|
impl AtomicTask {
|
||||||
/// Create an `AtomicTask` initialized with the given `Task`
|
/// Create an `AtomicTask` initialized with the given `Task`
|
||||||
@@ -69,7 +149,7 @@ impl AtomicTask {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers the task to be notified on calls to `notify`.
|
/// Registers the provided task to be notified on calls to `notify`.
|
||||||
///
|
///
|
||||||
/// The new task will take place of any previous tasks that were registered
|
/// The new task will take place of any previous tasks that were registered
|
||||||
/// by previous calls to `register`. Any calls to `notify` that happen after
|
/// by previous calls to `register`. Any calls to `notify` that happen after
|
||||||
@@ -84,36 +164,75 @@ impl AtomicTask {
|
|||||||
/// idea. Concurrent calls to `register` will attempt to register different
|
/// idea. Concurrent calls to `register` will attempt to register different
|
||||||
/// tasks to be notified. One of the callers will win and have its task set,
|
/// tasks to be notified. One of the callers will win and have its task set,
|
||||||
/// but there is no guarantee as to which caller will succeed.
|
/// but there is no guarantee as to which caller will succeed.
|
||||||
pub(crate) fn register(&self, task: Task) {
|
pub fn register_task(&self, task: Task) {
|
||||||
match self.state.compare_and_swap(WAITING, LOCKED_WRITE, Acquire) {
|
match self.state.compare_and_swap(WAITING, REGISTERING, Acquire) {
|
||||||
WAITING => {
|
WAITING => {
|
||||||
unsafe {
|
unsafe {
|
||||||
// Locked acquired, update the task cell
|
// Locked acquired, update the waker cell
|
||||||
*self.task.get() = Some(task);
|
*self.task.get() = Some(task.clone());
|
||||||
|
|
||||||
// Release the lock. If the state transitioned to
|
// Release the lock. If the state transitioned to include
|
||||||
// `LOCKED_NOTIFIED`, this means that an notify has been
|
// the `NOTIFYING` bit, this means that a notify has been
|
||||||
// signaled, so notify the task.
|
// called concurrently, so we have to remove the task and
|
||||||
if LOCKED_WRITE_NOTIFIED == self.state.swap(WAITING, Release) {
|
// notify it.`
|
||||||
(*self.task.get()).as_ref().unwrap().notify();
|
//
|
||||||
|
// Start by assuming that the state is `REGISTERING` as this
|
||||||
|
// is what we jut set it to.
|
||||||
|
let mut curr = REGISTERING;
|
||||||
|
|
||||||
|
// If a task has to be notified, it will be set here.
|
||||||
|
let mut notify: Option<Task> = None;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let res = self.state.compare_exchange(
|
||||||
|
curr, WAITING, AcqRel, Acquire);
|
||||||
|
|
||||||
|
match res {
|
||||||
|
Ok(_) => {
|
||||||
|
// The atomic exchange was successful, now
|
||||||
|
// notify the task (if set) and return.
|
||||||
|
if let Some(task) = notify {
|
||||||
|
task.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(actual) => {
|
||||||
|
// This branch can only be reached if a
|
||||||
|
// concurrent thread called `notify`. In this
|
||||||
|
// case, `actual` **must** be `REGISTERING |
|
||||||
|
// `NOTIFYING`.
|
||||||
|
debug_assert_eq!(actual, REGISTERING | NOTIFYING);
|
||||||
|
|
||||||
|
// Take the task to notify once the atomic operation has
|
||||||
|
// completed.
|
||||||
|
notify = (*self.task.get()).take();
|
||||||
|
|
||||||
|
// Update `curr` for the next iteration of the
|
||||||
|
// loop
|
||||||
|
curr = actual;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LOCKED_WRITE | LOCKED_WRITE_NOTIFIED => {
|
NOTIFYING => {
|
||||||
// A thread is concurrently calling `register`. This shouldn't
|
// Currently in the process of notifying the task, i.e.,
|
||||||
// happen as it doesn't really make much sense, but it isn't
|
// `notify` is currently being called on the old task handle.
|
||||||
// unsafe per se. Since two threads are concurrently trying to
|
// So, we call notify on the new task handle
|
||||||
// update the task, it's undefined which one "wins" (no ordering
|
task.notify();
|
||||||
// guarantees), so we can just do nothing.
|
|
||||||
}
|
}
|
||||||
state => {
|
state => {
|
||||||
debug_assert!(state != LOCKED_WRITE, "unexpected state LOCKED_WRITE");
|
// In this case, a concurrent thread is holding the
|
||||||
debug_assert!(state != LOCKED_WRITE_NOTIFIED, "unexpected state LOCKED_WRITE_NOTIFIED");
|
// "registering" lock. This probably indicates a bug in the
|
||||||
|
// caller's code as racing to call `register` doesn't make much
|
||||||
// Currently in a read locked state, this implies that `notify`
|
// sense.
|
||||||
// is currently being called on the old task handle. So, we call
|
//
|
||||||
// notify on the new task handle
|
// We just want to maintain memory safety. It is ok to drop the
|
||||||
task.notify();
|
// call to `register`.
|
||||||
|
debug_assert!(
|
||||||
|
state == REGISTERING ||
|
||||||
|
state == REGISTERING | NOTIFYING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,49 +241,33 @@ impl AtomicTask {
|
|||||||
///
|
///
|
||||||
/// If `register` has not been called yet, then this does nothing.
|
/// If `register` has not been called yet, then this does nothing.
|
||||||
pub fn notify(&self) {
|
pub fn notify(&self) {
|
||||||
let mut curr = WAITING;
|
// AcqRel ordering is used in order to acquire the value of the `task`
|
||||||
|
// cell as well as to establish a `release` ordering with whatever
|
||||||
|
// memory the `AtomicTask` is associated with.
|
||||||
|
match self.state.fetch_or(NOTIFYING, AcqRel) {
|
||||||
|
WAITING => {
|
||||||
|
// The notifying lock has been acquired.
|
||||||
|
let task = unsafe { (*self.task.get()).take() };
|
||||||
|
|
||||||
loop {
|
// Release the lock
|
||||||
if curr == LOCKED_WRITE {
|
self.state.fetch_and(!NOTIFYING, Release);
|
||||||
// Transition the state to LOCKED_NOTIFIED
|
|
||||||
let actual = self.state.compare_and_swap(LOCKED_WRITE, LOCKED_WRITE_NOTIFIED, Release);
|
|
||||||
|
|
||||||
if curr == actual {
|
if let Some(task) = task {
|
||||||
// Success, return
|
task.notify();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// update current state variable and try again
|
state => {
|
||||||
curr = actual;
|
// There is a concurrent thread currently updating the
|
||||||
|
// associated task.
|
||||||
} else if curr == LOCKED_WRITE_NOTIFIED {
|
//
|
||||||
// Currently in `LOCKED_WRITE_NOTIFIED` state, nothing else to do.
|
// Nothing more to do as the `NOTIFYING` bit has been set. It
|
||||||
return;
|
// doesn't matter if there are concurrent registering threads or
|
||||||
|
// not.
|
||||||
} else {
|
//
|
||||||
// Currently in a LOCKED_READ state, so attempt to increment the
|
debug_assert!(
|
||||||
// lock count.
|
state == REGISTERING ||
|
||||||
let actual = self.state.compare_and_swap(curr, curr + 1, Acquire);
|
state == REGISTERING | NOTIFYING ||
|
||||||
|
state == NOTIFYING);
|
||||||
// Locked acquired
|
|
||||||
if actual == curr {
|
|
||||||
// Notify the task
|
|
||||||
unsafe {
|
|
||||||
if let Some(ref task) = (*self.task.get()).take() {
|
|
||||||
task.notify();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Release the lock
|
|
||||||
self.state.fetch_sub(1, Release);
|
|
||||||
|
|
||||||
// Done
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// update current state variable and try again
|
|
||||||
curr = actual;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ impl Future for Shutdown {
|
|||||||
|
|
||||||
fn poll(&mut self) -> Poll<(), ()> {
|
fn poll(&mut self) -> Poll<(), ()> {
|
||||||
let task = Task::Futures1(task::current());
|
let task = Task::Futures1(task::current());
|
||||||
self.inner.shared.shutdown_task.register(task);
|
self.inner.shared.shutdown_task.register_task(task);
|
||||||
|
|
||||||
if !self.inner.is_shutdown() {
|
if !self.inner.is_shutdown() {
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ extern crate tokio_io;
|
|||||||
#[cfg(feature = "unstable-futures")]
|
#[cfg(feature = "unstable-futures")]
|
||||||
extern crate futures2;
|
extern crate futures2;
|
||||||
|
|
||||||
pub(crate) mod background;
|
|
||||||
mod atomic_task;
|
mod atomic_task;
|
||||||
|
pub(crate) mod background;
|
||||||
mod poll_evented;
|
mod poll_evented;
|
||||||
mod registration;
|
mod registration;
|
||||||
|
|
||||||
@@ -120,6 +120,9 @@ struct Inner {
|
|||||||
/// The underlying system event queue.
|
/// The underlying system event queue.
|
||||||
io: mio::Poll,
|
io: mio::Poll,
|
||||||
|
|
||||||
|
/// ABA guard counter
|
||||||
|
next_aba_guard: AtomicUsize,
|
||||||
|
|
||||||
/// Dispatch slabs for I/O and futures events
|
/// Dispatch slabs for I/O and futures events
|
||||||
io_dispatch: RwLock<Slab<ScheduledIo>>,
|
io_dispatch: RwLock<Slab<ScheduledIo>>,
|
||||||
|
|
||||||
@@ -128,6 +131,7 @@ struct Inner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct ScheduledIo {
|
struct ScheduledIo {
|
||||||
|
aba_guard: usize,
|
||||||
readiness: AtomicUsize,
|
readiness: AtomicUsize,
|
||||||
reader: AtomicTask,
|
reader: AtomicTask,
|
||||||
writer: AtomicTask,
|
writer: AtomicTask,
|
||||||
@@ -145,11 +149,11 @@ static HANDLE_FALLBACK: AtomicUsize = ATOMIC_USIZE_INIT;
|
|||||||
/// Tracks the reactor for the current execution context.
|
/// Tracks the reactor for the current execution context.
|
||||||
thread_local!(static CURRENT_REACTOR: RefCell<Option<Handle>> = RefCell::new(None));
|
thread_local!(static CURRENT_REACTOR: RefCell<Option<Handle>> = RefCell::new(None));
|
||||||
|
|
||||||
const TOKEN_WAKEUP: mio::Token = mio::Token(0);
|
const TOKEN_SHIFT: usize = 22;
|
||||||
const TOKEN_START: usize = 1;
|
|
||||||
|
|
||||||
// Kind of arbitrary, but this reserves some token space for later usage.
|
// Kind of arbitrary, but this reserves some token space for later usage.
|
||||||
const MAX_SOURCES: usize = usize::MAX >> 4;
|
const MAX_SOURCES: usize = (1 << TOKEN_SHIFT) - 1;
|
||||||
|
const TOKEN_WAKEUP: mio::Token = mio::Token(MAX_SOURCES);
|
||||||
|
|
||||||
fn _assert_kinds() {
|
fn _assert_kinds() {
|
||||||
fn _assert<T: Send + Sync>() {}
|
fn _assert<T: Send + Sync>() {}
|
||||||
@@ -221,6 +225,7 @@ impl Reactor {
|
|||||||
_wakeup_registration: wakeup_pair.0,
|
_wakeup_registration: wakeup_pair.0,
|
||||||
inner: Arc::new(Inner {
|
inner: Arc::new(Inner {
|
||||||
io: io,
|
io: io,
|
||||||
|
next_aba_guard: AtomicUsize::new(0),
|
||||||
io_dispatch: RwLock::new(Slab::with_capacity(1)),
|
io_dispatch: RwLock::new(Slab::with_capacity(1)),
|
||||||
wakeup: wakeup_pair.1,
|
wakeup: wakeup_pair.1,
|
||||||
}),
|
}),
|
||||||
@@ -358,10 +363,16 @@ impl Reactor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch(&self, token: mio::Token, ready: mio::Ready) {
|
fn dispatch(&self, token: mio::Token, ready: mio::Ready) {
|
||||||
let token = usize::from(token) - TOKEN_START;
|
let aba_guard = token.0 & !MAX_SOURCES;
|
||||||
|
let token = token.0 & MAX_SOURCES;
|
||||||
|
|
||||||
let io_dispatch = self.inner.io_dispatch.read().unwrap();
|
let io_dispatch = self.inner.io_dispatch.read().unwrap();
|
||||||
|
|
||||||
if let Some(io) = io_dispatch.get(token) {
|
if let Some(io) = io_dispatch.get(token) {
|
||||||
|
if aba_guard != io.aba_guard {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
io.readiness.fetch_or(ready.as_usize(), Relaxed);
|
io.readiness.fetch_or(ready.as_usize(), Relaxed);
|
||||||
|
|
||||||
if ready.is_writable() || platform::is_hup(&ready) {
|
if ready.is_writable() || platform::is_hup(&ready) {
|
||||||
@@ -545,6 +556,9 @@ impl Inner {
|
|||||||
fn add_source(&self, source: &Evented)
|
fn add_source(&self, source: &Evented)
|
||||||
-> io::Result<usize>
|
-> io::Result<usize>
|
||||||
{
|
{
|
||||||
|
// Get an ABA guard value
|
||||||
|
let aba_guard = self.next_aba_guard.fetch_add(1 << TOKEN_SHIFT, Relaxed);
|
||||||
|
|
||||||
let mut io_dispatch = self.io_dispatch.write().unwrap();
|
let mut io_dispatch = self.io_dispatch.write().unwrap();
|
||||||
|
|
||||||
if io_dispatch.len() == MAX_SOURCES {
|
if io_dispatch.len() == MAX_SOURCES {
|
||||||
@@ -554,13 +568,14 @@ impl Inner {
|
|||||||
|
|
||||||
// Acquire a write lock
|
// Acquire a write lock
|
||||||
let key = io_dispatch.insert(ScheduledIo {
|
let key = io_dispatch.insert(ScheduledIo {
|
||||||
|
aba_guard,
|
||||||
readiness: AtomicUsize::new(0),
|
readiness: AtomicUsize::new(0),
|
||||||
reader: AtomicTask::new(),
|
reader: AtomicTask::new(),
|
||||||
writer: AtomicTask::new(),
|
writer: AtomicTask::new(),
|
||||||
});
|
});
|
||||||
|
|
||||||
try!(self.io.register(source,
|
try!(self.io.register(source,
|
||||||
mio::Token(TOKEN_START + key),
|
mio::Token(aba_guard | key),
|
||||||
mio::Ready::all(),
|
mio::Ready::all(),
|
||||||
mio::PollOpt::edge()));
|
mio::PollOpt::edge()));
|
||||||
|
|
||||||
@@ -588,7 +603,7 @@ impl Inner {
|
|||||||
Direction::Write => (&sched.writer, mio::Ready::writable()),
|
Direction::Write => (&sched.writer, mio::Ready::writable()),
|
||||||
};
|
};
|
||||||
|
|
||||||
task.register(t);
|
task.register_task(t);
|
||||||
|
|
||||||
if sched.readiness.load(SeqCst) & ready.as_usize() != 0 {
|
if sched.readiness.load(SeqCst) & ready.as_usize() != 0 {
|
||||||
task.notify();
|
task.notify();
|
||||||
|
|||||||
@@ -647,9 +647,9 @@ impl<E: Evented + fmt::Debug> fmt::Debug for PollEvented<E> {
|
|||||||
|
|
||||||
impl<E: Evented> Drop for PollEvented<E> {
|
impl<E: Evented> Drop for PollEvented<E> {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if let Some(io) = self.io.as_ref() {
|
if let Some(io) = self.io.take() {
|
||||||
// Ignore errors
|
// Ignore errors
|
||||||
let _ = self.inner.registration.deregister(io);
|
let _ = self.inner.registration.deregister(&io);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use mio::{self, Evented};
|
|||||||
#[cfg(feature = "unstable-futures")]
|
#[cfg(feature = "unstable-futures")]
|
||||||
use futures2;
|
use futures2;
|
||||||
|
|
||||||
use std::{io, mem, usize};
|
use std::{io, ptr, usize};
|
||||||
use std::cell::UnsafeCell;
|
use std::cell::UnsafeCell;
|
||||||
use std::sync::atomic::AtomicUsize;
|
use std::sync::atomic::AtomicUsize;
|
||||||
use std::sync::atomic::Ordering::SeqCst;
|
use std::sync::atomic::Ordering::SeqCst;
|
||||||
@@ -68,7 +68,7 @@ struct Inner {
|
|||||||
struct Node {
|
struct Node {
|
||||||
direction: Direction,
|
direction: Direction,
|
||||||
task: Task,
|
task: Task,
|
||||||
next: Option<Box<Node>>,
|
next: *mut Node,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initial state. The handle is not set and the registration is idle.
|
/// Initial state. The handle is not set and the registration is idle.
|
||||||
@@ -197,40 +197,35 @@ impl Registration {
|
|||||||
// are pending readiness notifications.
|
// are pending readiness notifications.
|
||||||
let actual = self.state.swap(READY, SeqCst);
|
let actual = self.state.swap(READY, SeqCst);
|
||||||
|
|
||||||
// Consume the stack of nodes.
|
// Consume the stack of nodes
|
||||||
let ptr = actual & !LIFECYCLE_MASK;
|
|
||||||
|
|
||||||
if ptr != 0 {
|
let mut read = false;
|
||||||
let mut read = false;
|
let mut write = false;
|
||||||
let mut write = false;
|
let mut ptr = (actual & !LIFECYCLE_MASK) as *mut Node;
|
||||||
let mut curr = unsafe { Box::from_raw(ptr as *mut Node) };
|
|
||||||
|
|
||||||
let inner = unsafe { (*self.inner.get()).as_ref().unwrap() };
|
let inner = unsafe { (*self.inner.get()).as_ref().unwrap() };
|
||||||
|
|
||||||
loop {
|
while !ptr.is_null() {
|
||||||
let node = *curr;
|
let node = unsafe { Box::from_raw(ptr) };
|
||||||
let Node {
|
let node = *node;
|
||||||
direction,
|
let Node {
|
||||||
task,
|
direction,
|
||||||
next,
|
task,
|
||||||
} = node;
|
next,
|
||||||
|
} = node;
|
||||||
|
|
||||||
let flag = match direction {
|
let flag = match direction {
|
||||||
Direction::Read => &mut read,
|
Direction::Read => &mut read,
|
||||||
Direction::Write => &mut write,
|
Direction::Write => &mut write,
|
||||||
};
|
};
|
||||||
|
|
||||||
if !*flag {
|
if !*flag {
|
||||||
*flag = true;
|
*flag = true;
|
||||||
|
|
||||||
inner.register(direction, task);
|
inner.register(direction, task);
|
||||||
}
|
|
||||||
|
|
||||||
match next {
|
|
||||||
Some(next) => curr = next,
|
|
||||||
None => break,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ptr = next;
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.map(|_| true);
|
return res.map(|_| true);
|
||||||
@@ -388,41 +383,35 @@ impl Registration {
|
|||||||
let inner = unsafe { (*self.inner.get()).as_ref().unwrap() };
|
let inner = unsafe { (*self.inner.get()).as_ref().unwrap() };
|
||||||
return inner.poll_ready(direction, notify, task);
|
return inner.poll_ready(direction, notify, task);
|
||||||
}
|
}
|
||||||
_ => {
|
LOCKED => {
|
||||||
if !notify {
|
if !notify {
|
||||||
// Skip the notification tracking junk.
|
// Skip the notification tracking junk.
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let ptr = state & !LIFECYCLE_MASK;
|
let next_ptr = (state & !LIFECYCLE_MASK) as *mut Node;
|
||||||
|
|
||||||
|
let task = task();
|
||||||
|
|
||||||
// Get the node
|
// Get the node
|
||||||
let mut n = node.take().unwrap_or_else(|| {
|
let mut n = node.take().unwrap_or_else(|| {
|
||||||
Box::new(Node {
|
Box::new(Node {
|
||||||
direction,
|
direction,
|
||||||
task: task(),
|
task: task,
|
||||||
next: None,
|
next: ptr::null_mut(),
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
n.next = if ptr == 0 {
|
n.next = next_ptr;
|
||||||
None
|
|
||||||
} else {
|
|
||||||
// Great care must be taken of the CAS fails
|
|
||||||
Some(unsafe { Box::from_raw(ptr as *mut Node) })
|
|
||||||
};
|
|
||||||
|
|
||||||
let ptr = Box::into_raw(n);
|
let node_ptr = Box::into_raw(n);
|
||||||
let next = ptr as usize | (state & LIFECYCLE_MASK);
|
let next = node_ptr as usize | (state & LIFECYCLE_MASK);
|
||||||
|
|
||||||
let actual = self.state.compare_and_swap(state, next, SeqCst);
|
let actual = self.state.compare_and_swap(state, next, SeqCst);
|
||||||
|
|
||||||
if actual != state {
|
if actual != state {
|
||||||
// Back out of the node boxing
|
// Back out of the node boxing
|
||||||
let mut n = unsafe { Box::from_raw(ptr) };
|
let n = unsafe { Box::from_raw(node_ptr) };
|
||||||
|
|
||||||
// We don't really own this
|
|
||||||
mem::forget(n.next.take());
|
|
||||||
|
|
||||||
// Save this for next loop
|
// Save this for next loop
|
||||||
node = Some(n);
|
node = Some(n);
|
||||||
@@ -433,6 +422,7 @@ impl Registration {
|
|||||||
|
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -532,10 +522,11 @@ impl Inner {
|
|||||||
sched.readiness.fetch_and(!mask_no_hup, SeqCst));
|
sched.readiness.fetch_and(!mask_no_hup, SeqCst));
|
||||||
|
|
||||||
if ready.is_empty() && notify {
|
if ready.is_empty() && notify {
|
||||||
|
let task = task();
|
||||||
// Update the task info
|
// Update the task info
|
||||||
match direction {
|
match direction {
|
||||||
Direction::Read => sched.reader.register(task()),
|
Direction::Read => sched.reader.register_task(task),
|
||||||
Direction::Write => sched.writer.register(task()),
|
Direction::Write => sched.writer.register_task(task),
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try again
|
// Try again
|
||||||
|
|||||||
@@ -936,9 +936,10 @@ impl Future for Shutdown {
|
|||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<(), ()> {
|
fn poll(&mut self) -> Poll<(), ()> {
|
||||||
|
use futures::task;
|
||||||
trace!("Shutdown::poll");
|
trace!("Shutdown::poll");
|
||||||
|
|
||||||
self.inner().shutdown_task.task1.register();
|
self.inner().shutdown_task.task1.register_task(task::current());
|
||||||
|
|
||||||
if 0 != self.inner().num_workers.load(Acquire) {
|
if 0 != self.inner().num_workers.load(Acquire) {
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
|
|||||||
@@ -222,13 +222,13 @@ impl Task {
|
|||||||
let actual = self.inner().state.compare_and_swap(
|
let actual = self.inner().state.compare_and_swap(
|
||||||
Idle.into(),
|
Idle.into(),
|
||||||
Scheduled.into(),
|
Scheduled.into(),
|
||||||
Relaxed).into();
|
AcqRel).into();
|
||||||
|
|
||||||
match actual {
|
match actual {
|
||||||
Idle => return true,
|
Idle => return true,
|
||||||
Running => {
|
Running => {
|
||||||
let actual = self.inner().state.compare_and_swap(
|
let actual = self.inner().state.compare_and_swap(
|
||||||
Running.into(), Notified.into(), Relaxed).into();
|
Running.into(), Notified.into(), AcqRel).into();
|
||||||
|
|
||||||
match actual {
|
match actual {
|
||||||
Idle => continue,
|
Idle => continue,
|
||||||
|
|||||||
@@ -186,7 +186,7 @@ fn force_shutdown_drops_futures() {
|
|||||||
let a = num_inc.clone();
|
let a = num_inc.clone();
|
||||||
let b = num_dec.clone();
|
let b = num_dec.clone();
|
||||||
|
|
||||||
let mut pool = Builder::new()
|
let pool = Builder::new()
|
||||||
.around_worker(move |w, _| {
|
.around_worker(move |w, _| {
|
||||||
a.fetch_add(1, Relaxed);
|
a.fetch_add(1, Relaxed);
|
||||||
w.run();
|
w.run();
|
||||||
@@ -548,3 +548,103 @@ fn panic_in_task() {
|
|||||||
|
|
||||||
await_shutdown(pool.shutdown_on_idle());
|
await_shutdown(pool.shutdown_on_idle());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg(not(feature = "unstable-futures"))]
|
||||||
|
fn hammer() {
|
||||||
|
use futures::future;
|
||||||
|
use futures::sync::{oneshot, mpsc};
|
||||||
|
|
||||||
|
const N: usize = 1000;
|
||||||
|
const ITER: usize = 20;
|
||||||
|
|
||||||
|
struct Counted<T> {
|
||||||
|
cnt: Arc<AtomicUsize>,
|
||||||
|
inner: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Future> Future for Counted<T> {
|
||||||
|
type Item = T::Item;
|
||||||
|
type Error = T::Error;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<T::Item, T::Error> {
|
||||||
|
self.inner.poll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Drop for Counted<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.cnt.fetch_add(1, Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for i in 0.. ITER {
|
||||||
|
println!("~~~ ITER {} ~~~", i);
|
||||||
|
|
||||||
|
let pool = Builder::new()
|
||||||
|
// .pool_size(30)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
let cnt = Arc::new(AtomicUsize::new(0));
|
||||||
|
|
||||||
|
let (listen_tx, listen_rx) = mpsc::unbounded::<oneshot::Sender<oneshot::Sender<()>>>();
|
||||||
|
let mut listen_tx = listen_tx.wait();
|
||||||
|
|
||||||
|
pool.spawn({
|
||||||
|
let c1 = cnt.clone();
|
||||||
|
let c2 = cnt.clone();
|
||||||
|
let pool = pool.sender().clone();
|
||||||
|
let task = listen_rx
|
||||||
|
.map_err(|e| panic!("accept error = {:?}", e))
|
||||||
|
.for_each(move |tx| {
|
||||||
|
let task = future::lazy(|| {
|
||||||
|
let (tx2, rx2) = oneshot::channel();
|
||||||
|
|
||||||
|
tx.send(tx2).unwrap();
|
||||||
|
rx2
|
||||||
|
})
|
||||||
|
.map_err(|e| panic!("e={:?}", e))
|
||||||
|
.and_then(|_| {
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
pool.spawn(Counted {
|
||||||
|
inner: task,
|
||||||
|
cnt: c1.clone(),
|
||||||
|
}).unwrap();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
Counted {
|
||||||
|
inner: task,
|
||||||
|
cnt: c2,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for _ in 0..N {
|
||||||
|
let cnt = cnt.clone();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
listen_tx.send(tx).unwrap();
|
||||||
|
|
||||||
|
pool.spawn({
|
||||||
|
let task = rx
|
||||||
|
.map_err(|e| panic!("rx err={:?}", e))
|
||||||
|
.and_then(|tx| {
|
||||||
|
tx.send(()).unwrap();
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
Counted {
|
||||||
|
inner: task,
|
||||||
|
cnt,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(listen_tx);
|
||||||
|
|
||||||
|
pool.shutdown_on_idle().wait().unwrap();
|
||||||
|
assert_eq!(N * 2 + 1, cnt.load(Relaxed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user