]> git.lizzy.rs Git - rust.git/blob - src/test/bench/shootout-threadring.rs
cfb950090a2cf78acadb7d6c97c47050b0168960
[rust.git] / src / test / bench / shootout-threadring.rs
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 use std::os;
14
15 fn start(n_tasks: int, token: int) {
16     let (tx, mut rx) = channel();
17     tx.send(token);
18     //  XXX could not get this to work with a range closure
19     let mut i = 2;
20     while i <= n_tasks {
21         let (tx, next_rx) = channel();
22         let imm_i = i;
23         let imm_rx = rx;
24         spawn(proc() {
25             roundtrip(imm_i, n_tasks, &imm_rx, &tx);
26         });
27         rx = next_rx;
28         i += 1;
29     }
30     let imm_rx = rx;
31     spawn(proc() {
32         roundtrip(1, n_tasks, &imm_rx, &tx);
33     });
34 }
35
36 fn roundtrip(id: int, n_tasks: int, p: &Receiver<int>, ch: &Sender<int>) {
37     loop {
38         match p.recv() {
39           1 => {
40             println!("{}\n", id);
41             return;
42           }
43           token => {
44             println!("thread: {}   got token: {}", id, token);
45             ch.send(token - 1);
46             if token <= n_tasks {
47                 return;
48             }
49           }
50         }
51     }
52 }
53
54 fn main() {
55     use std::from_str::FromStr;
56
57     let args = if os::getenv("RUST_BENCH").is_some() {
58         vec!(~"", ~"2000000", ~"503")
59     }
60     else {
61         os::args()
62     };
63     let token = if args.len() > 1u {
64         FromStr::from_str(args[1]).unwrap()
65     }
66     else {
67         1000
68     };
69     let n_tasks = if args.len() > 2u {
70         FromStr::from_str(args[2]).unwrap()
71     }
72     else {
73         503
74     };
75     start(n_tasks, token);
76
77 }