|
| 1 | +// Copyright 2012 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. |
| 4 | +// |
| 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. |
| 10 | + |
| 11 | +// Based on threadring.erlang by Jira Isa |
| 12 | + |
| 13 | +fn start(n_tasks: int, token: int) { |
| 14 | + let mut (p, ch1) = comm::stream(); |
| 15 | + ch1.send(token); |
| 16 | + // XXX could not get this to work with a range closure |
| 17 | + let mut i = 2; |
| 18 | + while i <= n_tasks { |
| 19 | + let (next_p, ch) = comm::stream(); |
| 20 | + let imm_i = i; |
| 21 | + let imm_p = p; |
| 22 | + do task::spawn { |
| 23 | + roundtrip(imm_i, n_tasks, &imm_p, &ch); |
| 24 | + }; |
| 25 | + p = next_p; |
| 26 | + i += 1; |
| 27 | + } |
| 28 | + let imm_p = p; |
| 29 | + let imm_ch = ch1; |
| 30 | + do task::spawn { |
| 31 | + roundtrip(1, n_tasks, &imm_p, &imm_ch); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn roundtrip(id: int, n_tasks: int, p: &comm::Port<int>, ch: &comm::Chan<int>) { |
| 36 | + while (true) { |
| 37 | + match p.recv() { |
| 38 | + 1 => { |
| 39 | + io::println(fmt!("%d\n", id)); |
| 40 | + return; |
| 41 | + } |
| 42 | + token => { |
| 43 | + debug!("thread: %d got token: %d", id, token); |
| 44 | + ch.send(token - 1); |
| 45 | + if token <= n_tasks { |
| 46 | + return; |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +fn main() { |
| 54 | + let args = if os::getenv(~"RUST_BENCH").is_some() { |
| 55 | + ~[~"", ~"2000000", ~"503"] |
| 56 | + } |
| 57 | + else { |
| 58 | + os::args() |
| 59 | + }; |
| 60 | + let token = if args.len() > 1u { |
| 61 | + int::from_str(args[1]).get() |
| 62 | + } |
| 63 | + else { |
| 64 | + 1000 |
| 65 | + }; |
| 66 | + let n_tasks = if args.len() > 2u { |
| 67 | + int::from_str(args[2]).get() |
| 68 | + } |
| 69 | + else { |
| 70 | + 503 |
| 71 | + }; |
| 72 | + start(n_tasks, token); |
| 73 | + |
| 74 | +} |
0 commit comments