File: task-comm-3.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (66 lines) | stat: -rw-r--r-- 1,499 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//@ run-pass
#![allow(unused_must_use)]
//@ needs-threads

use std::sync::mpsc::{channel, Sender};
use std::thread;

pub fn main() {
    println!("===== WITHOUT THREADS =====");
    test00();
}

fn test00_start(ch: &Sender<isize>, message: isize, count: isize) {
    println!("Starting test00_start");
    let mut i: isize = 0;
    while i < count {
        println!("Sending Message");
        ch.send(message + 0).unwrap();
        i = i + 1;
    }
    println!("Ending test00_start");
}

fn test00() {
    let number_of_tasks: isize = 16;
    let number_of_messages: isize = 4;

    println!("Creating tasks");

    let (tx, rx) = channel();

    let mut i: isize = 0;

    // Create and spawn threads...
    let mut results = Vec::new();
    while i < number_of_tasks {
        let tx = tx.clone();
        results.push(thread::spawn({
            let i = i;
            move || test00_start(&tx, i, number_of_messages)
        }));
        i = i + 1;
    }

    // Read from spawned threads...
    let mut sum = 0;
    for _r in &results {
        i = 0;
        while i < number_of_messages {
            let value = rx.recv().unwrap();
            sum += value;
            i = i + 1;
        }
    }

    // Join spawned threads...
    for r in results {
        r.join();
    }

    println!("Completed: Final number is: ");
    println!("{}", sum);
    // assert (sum == (((number_of_threads * (number_of_threads - 1)) / 2) *
    //       number_of_messages));
    assert_eq!(sum, 480);
}