use cell::Cell;
use cmp::Eq;
use option;
use result::Result;
use comm::{stream, Chan, GenericChan, GenericPort, Port, SharedChan};
use prelude::*;
use result;
use task::rt::{task_id, sched_id, rust_task};
use util;
use util::replace;
mod local_data_priv;
pub mod local_data;
pub mod rt;
pub mod spawn;
#[deriving_eq]
pub enum Scheduler {
SchedulerHandle(sched_id)
}
#[deriving_eq]
pub enum Task {
TaskHandle(task_id)
}
pub enum TaskResult {
Success,
Failure,
}
impl Eq for TaskResult {
pure fn eq(&self, other: &TaskResult) -> bool {
match ((*self), (*other)) {
(Success, Success) | (Failure, Failure) => true,
(Success, _) | (Failure, _) => false
}
}
pure fn ne(&self, other: &TaskResult) -> bool { !(*self).eq(other) }
}
#[deriving_eq]
pub enum SchedMode {
DefaultScheduler,
CurrentScheduler,
ExistingScheduler(Scheduler),
PlatformThread,
SingleThreaded,
ThreadPerCore,
ThreadPerTask,
ManualThreads(uint),
}
pub struct SchedOpts {
mode: SchedMode,
foreign_stack_size: Option<uint>,
}
pub struct TaskOpts {
linked: bool,
supervised: bool,
mut notify_chan: Option<Chan<TaskResult>>,
sched: SchedOpts
}
pub struct TaskBuilder {
opts: TaskOpts,
gen_body: @fn(v: ~fn()) -> ~fn(),
can_not_copy: Option<util::NonCopyable>,
mut consumed: bool,
}
pub fn task() -> TaskBuilder {
TaskBuilder {
opts: default_task_opts(),
gen_body: |body| body, can_not_copy: None,
mut consumed: false,
}
}
#[doc(hidden)] priv impl TaskBuilder {
fn consume(&self) -> TaskBuilder {
if self.consumed {
fail!(~"Cannot copy a task_builder"); }
self.consumed = true;
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: self.opts.linked,
supervised: self.opts.supervised,
notify_chan: notify_chan,
sched: self.opts.sched
},
gen_body: self.gen_body,
can_not_copy: None,
consumed: false
}
}
}
pub impl TaskBuilder {
fn unlinked(&self) -> TaskBuilder {
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: false,
supervised: self.opts.supervised,
notify_chan: notify_chan,
sched: self.opts.sched
},
can_not_copy: None,
.. self.consume()
}
}
fn supervised(&self) -> TaskBuilder {
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: false,
supervised: true,
notify_chan: notify_chan,
sched: self.opts.sched
},
can_not_copy: None,
.. self.consume()
}
}
fn linked(&self) -> TaskBuilder {
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: true,
supervised: false,
notify_chan: notify_chan,
sched: self.opts.sched
},
can_not_copy: None,
.. self.consume()
}
}
fn future_result(&self, blk: fn(v: Port<TaskResult>)) -> TaskBuilder {
if self.opts.notify_chan.is_some() {
fail!(~"Can't set multiple future_results for one task!");
}
let (notify_pipe_po, notify_pipe_ch) = stream::<TaskResult>();
blk(notify_pipe_po);
TaskBuilder {
opts: TaskOpts {
linked: self.opts.linked,
supervised: self.opts.supervised,
notify_chan: Some(notify_pipe_ch),
sched: self.opts.sched
},
can_not_copy: None,
.. self.consume()
}
}
fn sched_mode(&self, mode: SchedMode) -> TaskBuilder {
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: self.opts.linked,
supervised: self.opts.supervised,
notify_chan: notify_chan,
sched: SchedOpts { mode: mode, foreign_stack_size: None}
},
can_not_copy: None,
.. self.consume()
}
}
fn add_wrapper(&self, wrapper: @fn(v: ~fn()) -> ~fn()) -> TaskBuilder {
let prev_gen_body = self.gen_body;
let notify_chan = replace(&mut self.opts.notify_chan, None);
TaskBuilder {
opts: TaskOpts {
linked: self.opts.linked,
supervised: self.opts.supervised,
notify_chan: notify_chan,
sched: self.opts.sched
},
gen_body: |body| { wrapper(prev_gen_body(body)) },
can_not_copy: None,
.. self.consume()
}
}
fn spawn(&self, f: ~fn()) {
let notify_chan = replace(&mut self.opts.notify_chan, None);
let x = self.consume();
let opts = TaskOpts {
linked: x.opts.linked,
supervised: x.opts.supervised,
notify_chan: notify_chan,
sched: x.opts.sched
};
spawn::spawn_raw(opts, (x.gen_body)(f));
}
fn spawn_with<A:Owned>(&self, arg: A, f: ~fn(v: A)) {
let arg = Cell(arg);
do self.spawn {
f(arg.take());
}
}
fn try<T:Owned>(&self, f: ~fn() -> T) -> Result<T,()> {
let (po, ch) = stream::<T>();
let mut result = None;
let fr_task_builder = self.future_result(|+r| {
result = Some(r);
});
do fr_task_builder.spawn || {
ch.send(f());
}
match option::unwrap(result).recv() {
Success => result::Ok(po.recv()),
Failure => result::Err(())
}
}
}
pub fn default_task_opts() -> TaskOpts {
TaskOpts {
linked: true,
supervised: false,
notify_chan: None,
sched: SchedOpts {
mode: DefaultScheduler,
foreign_stack_size: None
}
}
}
pub fn spawn(f: ~fn()) {
task().spawn(f)
}
pub fn spawn_unlinked(f: ~fn()) {
task().unlinked().spawn(f)
}
pub fn spawn_supervised(f: ~fn()) {
task().supervised().spawn(f)
}
pub fn spawn_with<A:Owned>(arg: A, f: ~fn(v: A)) {
task().spawn_with(arg, f)
}
pub fn spawn_sched(mode: SchedMode, f: ~fn()) {
task().sched_mode(mode).spawn(f)
}
pub fn try<T:Owned>(f: ~fn() -> T) -> Result<T,()> {
task().supervised().try(f)
}
pub fn yield() {
unsafe {
let task_ = rt::rust_get_task();
let killed = rt::rust_task_yield(task_);
if killed && !failing() {
fail!(~"killed");
}
}
}
pub fn failing() -> bool {
unsafe {
rt::rust_task_is_unwinding(rt::rust_get_task())
}
}
pub fn get_task() -> Task {
unsafe {
TaskHandle(rt::get_task_id())
}
}
pub fn get_scheduler() -> Scheduler {
SchedulerHandle(unsafe { rt::rust_get_sched_id() })
}
pub unsafe fn unkillable<U>(f: fn() -> U) -> U {
struct AllowFailure {
t: *rust_task,
drop {
unsafe {
rt::rust_task_allow_kill(self.t);
}
}
}
fn AllowFailure(t: *rust_task) -> AllowFailure{
AllowFailure {
t: t
}
}
unsafe {
let t = rt::rust_get_task();
let _allow_failure = AllowFailure(t);
rt::rust_task_inhibit_kill(t);
f()
}
}
pub unsafe fn rekillable<U>(f: fn() -> U) -> U {
struct DisallowFailure {
t: *rust_task,
drop {
unsafe {
rt::rust_task_inhibit_kill(self.t);
}
}
}
fn DisallowFailure(t: *rust_task) -> DisallowFailure {
DisallowFailure {
t: t
}
}
unsafe {
let t = rt::rust_get_task();
let _allow_failure = DisallowFailure(t);
rt::rust_task_allow_kill(t);
f()
}
}
pub unsafe fn atomically<U>(f: fn() -> U) -> U {
struct DeferInterrupts {
t: *rust_task,
drop {
unsafe {
rt::rust_task_allow_yield(self.t);
rt::rust_task_allow_kill(self.t);
}
}
}
fn DeferInterrupts(t: *rust_task) -> DeferInterrupts {
DeferInterrupts {
t: t
}
}
unsafe {
let t = rt::rust_get_task();
let _interrupts = DeferInterrupts(t);
rt::rust_task_inhibit_kill(t);
rt::rust_task_inhibit_yield(t);
f()
}
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_cant_dup_task_builder() {
let b = task().unlinked();
do b.spawn { }
do b.spawn { } }
#[test] #[ignore(cfg(windows))]
fn test_spawn_unlinked_unsup_no_fail_down() { let (po, ch) = stream();
let ch = SharedChan(ch);
do spawn_unlinked {
let ch = ch.clone();
do spawn_unlinked {
for iter::repeat(16) { task::yield(); }
ch.send(()); }
fail!(); }
po.recv();
}
#[test] #[ignore(cfg(windows))]
fn test_spawn_unlinked_unsup_no_fail_up() { do spawn_unlinked { fail!(); }
}
#[test] #[ignore(cfg(windows))]
fn test_spawn_unlinked_sup_no_fail_up() { do spawn_supervised { fail!(); }
for iter::repeat(16) { task::yield(); }
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_unlinked_sup_fail_down() {
do spawn_supervised { loop { task::yield(); } }
fail!(); }
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_sup_fail_up() { let (po, _ch) = stream::<()>();
let opts = {
let mut opts = default_task_opts();
opts.linked = true;
opts.supervised = true;
opts
};
let b0 = task();
let b1 = TaskBuilder {
opts: opts,
can_not_copy: None,
.. b0
};
do b1.spawn { fail!(); }
po.recv(); }
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_sup_fail_down() { let opts = {
let mut opts = default_task_opts();
opts.linked = true;
opts.supervised = true;
opts
};
let b0 = task();
let b1 = TaskBuilder {
opts: opts,
can_not_copy: None,
.. b0
};
do b1.spawn { loop { task::yield(); } }
fail!(); }
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_unsup_fail_up() { let (po, _ch) = stream::<()>();
do spawn { fail!(); }
po.recv(); }
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_unsup_fail_down() { do spawn { loop { task::yield(); } }
fail!();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_unsup_default_opts() { do task().linked().spawn { loop { task::yield(); } }
fail!();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_failure_propagate_grandchild() {
do spawn_supervised {
do spawn_supervised {
loop { task::yield(); }
}
}
for iter::repeat(16) { task::yield(); }
fail!();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_failure_propagate_secondborn() {
do spawn_supervised {
do spawn { loop { task::yield(); }
}
}
for iter::repeat(16) { task::yield(); }
fail!();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_failure_propagate_nephew_or_niece() {
do spawn { do spawn_supervised {
loop { task::yield(); }
}
}
for iter::repeat(16) { task::yield(); }
fail!();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_spawn_linked_sup_propagate_sibling() {
do spawn { do spawn { loop { task::yield(); }
}
}
for iter::repeat(16) { task::yield(); }
fail!();
}
#[test]
fn test_run_basic() {
let (po, ch) = stream::<()>();
do task().spawn {
ch.send(());
}
po.recv();
}
#[test]
struct Wrapper {
mut f: Option<Chan<()>>
}
#[test]
fn test_add_wrapper() {
let (po, ch) = stream::<()>();
let b0 = task();
let ch = Wrapper { f: Some(ch) };
let b1 = do b0.add_wrapper |body| {
let ch = Wrapper { f: Some(ch.f.swap_unwrap()) };
let result: ~fn() = || {
let ch = ch.f.swap_unwrap();
body();
ch.send(());
};
result
};
do b1.spawn { }
po.recv();
}
#[test]
#[ignore(cfg(windows))]
fn test_future_result() {
let mut result = None;
do task().future_result(|+r| { result = Some(r); }).spawn { }
assert option::unwrap(result).recv() == Success;
result = None;
do task().future_result(|+r|
{ result = Some(r); }).unlinked().spawn {
fail!();
}
assert option::unwrap(result).recv() == Failure;
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_back_to_the_future_result() {
let _ = task().future_result(util::ignore).future_result(util::ignore);
}
#[test]
fn test_try_success() {
match do try {
~"Success!"
} {
result::Ok(~"Success!") => (),
_ => fail!()
}
}
#[test]
#[ignore(cfg(windows))]
fn test_try_fail() {
match do try {
fail!()
} {
result::Err(()) => (),
result::Ok(()) => fail!()
}
}
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_spawn_sched_no_threads() {
do spawn_sched(ManualThreads(0u)) { }
}
#[test]
fn test_spawn_sched() {
let (po, ch) = stream::<()>();
let ch = SharedChan(ch);
fn f(i: int, ch: SharedChan<()>) {
let parent_sched_id = unsafe { rt::rust_get_sched_id() };
do spawn_sched(SingleThreaded) {
let child_sched_id = unsafe { rt::rust_get_sched_id() };
assert parent_sched_id != child_sched_id;
if (i == 0) {
ch.send(());
} else {
f(i - 1, ch.clone());
}
};
}
f(10, ch);
po.recv();
}
#[test]
fn test_spawn_sched_childs_on_default_sched() {
let (po, ch) = stream();
let default_id = unsafe { rt::rust_get_sched_id() };
let ch = Wrapper { f: Some(ch) };
do spawn_sched(SingleThreaded) {
let parent_sched_id = unsafe { rt::rust_get_sched_id() };
let ch = Wrapper { f: Some(ch.f.swap_unwrap()) };
do spawn {
let ch = ch.f.swap_unwrap();
let child_sched_id = unsafe { rt::rust_get_sched_id() };
assert parent_sched_id != child_sched_id;
assert child_sched_id == default_id;
ch.send(());
};
};
po.recv();
}
#[nolink]
#[cfg(test)]
extern mod testrt {
unsafe fn rust_dbg_lock_create() -> *libc::c_void;
unsafe fn rust_dbg_lock_destroy(lock: *libc::c_void);
unsafe fn rust_dbg_lock_lock(lock: *libc::c_void);
unsafe fn rust_dbg_lock_unlock(lock: *libc::c_void);
unsafe fn rust_dbg_lock_wait(lock: *libc::c_void);
unsafe fn rust_dbg_lock_signal(lock: *libc::c_void);
}
#[test]
fn test_spawn_sched_blocking() {
unsafe {
for iter::repeat(20u) {
let (start_po, start_ch) = stream();
let (fin_po, fin_ch) = stream();
let lock = testrt::rust_dbg_lock_create();
do spawn_sched(SingleThreaded) {
unsafe {
testrt::rust_dbg_lock_lock(lock);
start_ch.send(());
testrt::rust_dbg_lock_wait(lock);
testrt::rust_dbg_lock_unlock(lock);
fin_ch.send(());
}
};
start_po.recv();
fn pingpong(po: &Port<int>, ch: &Chan<int>) {
let mut val = 20;
while val > 0 {
val = po.recv();
ch.send(val - 1);
}
}
let (setup_po, setup_ch) = stream();
let (parent_po, parent_ch) = stream();
do spawn {
let (child_po, child_ch) = stream();
setup_ch.send(child_ch);
pingpong(&child_po, &parent_ch);
};
let child_ch = setup_po.recv();
child_ch.send(20);
pingpong(&parent_po, &child_ch);
testrt::rust_dbg_lock_lock(lock);
testrt::rust_dbg_lock_signal(lock);
testrt::rust_dbg_lock_unlock(lock);
fin_po.recv();
testrt::rust_dbg_lock_destroy(lock);
}
}
}
#[cfg(test)]
fn avoid_copying_the_body(spawnfn: &fn(v: ~fn())) {
let (p, ch) = stream::<uint>();
let x = ~1;
let x_in_parent = ptr::addr_of(&(*x)) as uint;
do spawnfn || {
let x_in_child = ptr::addr_of(&(*x)) as uint;
ch.send(x_in_child);
}
let x_in_child = p.recv();
assert x_in_parent == x_in_child;
}
#[test]
fn test_avoid_copying_the_body_spawn() {
avoid_copying_the_body(spawn);
}
#[test]
fn test_avoid_copying_the_body_task_spawn() {
do avoid_copying_the_body |f| {
do task().spawn || {
f();
}
}
}
#[test]
fn test_avoid_copying_the_body_try() {
do avoid_copying_the_body |f| {
do try || {
f()
};
}
}
#[test]
fn test_avoid_copying_the_body_unlinked() {
do avoid_copying_the_body |f| {
do spawn_unlinked || {
f();
}
}
}
#[test]
fn test_platform_thread() {
let (po, ch) = stream();
do task().sched_mode(PlatformThread).spawn {
ch.send(());
}
po.recv();
}
#[test]
#[ignore(cfg(windows))]
#[should_fail]
fn test_unkillable() {
let (po, ch) = stream();
do spawn_unlinked {
for iter::repeat(10) { yield() }
ch.send(());
}
do spawn {
yield();
fail!();
}
unsafe {
do unkillable {
let p = ~0;
let pp: *uint = cast::transmute(p);
po.recv();
let _p: ~int = cast::transmute(pp);
}
}
po.recv();
}
#[test]
#[ignore(cfg(windows))]
#[should_fail]
fn test_unkillable_nested() {
let (po, ch) = comm::stream();
do spawn_unlinked || {
for iter::repeat(10) { yield() }
ch.send(());
}
do spawn {
yield();
fail!();
}
unsafe {
do unkillable {
do unkillable {} let p = ~0;
let pp: *uint = cast::transmute(p);
po.recv();
let _p: ~int = cast::transmute(pp);
}
}
po.recv();
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_atomically() {
unsafe { do atomically { yield(); } }
}
#[test]
fn test_atomically2() {
unsafe { do atomically { } } yield(); }
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_atomically_nested() {
unsafe { do atomically { do atomically { } yield(); } }
}
#[test]
fn test_child_doesnt_ref_parent() {
const generations: uint = 16;
fn child_no(x: uint) -> ~fn() {
return || {
if x < generations {
task::spawn(child_no(x+1));
}
}
}
task::spawn(child_no(0));
}
#[test]
fn test_sched_thread_per_core() {
let (port, chan) = comm::stream();
do spawn_sched(ThreadPerCore) || {
unsafe {
let cores = rt::rust_num_threads();
let reported_threads = rt::rust_sched_threads();
assert(cores as uint == reported_threads as uint);
chan.send(());
}
}
port.recv();
}
#[test]
fn test_spawn_thread_on_demand() {
let (port, chan) = comm::stream();
do spawn_sched(ManualThreads(2)) || {
unsafe {
let max_threads = rt::rust_sched_threads();
assert(max_threads as int == 2);
let running_threads = rt::rust_sched_current_nonlazy_threads();
assert(running_threads as int == 1);
let (port2, chan2) = comm::stream();
do spawn_sched(CurrentScheduler) || {
chan2.send(());
}
let running_threads2 = rt::rust_sched_current_nonlazy_threads();
assert(running_threads2 as int == 2);
port2.recv();
chan.send(());
}
}
port.recv();
}