1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paiza.ioでrust その14

Posted at

概要

paiza.ioでrustやってみた。
練習問題やってみた。

練習問題

threadを使え。

参考にしたページ

サンプルコード

use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::thread;
use std::process::exit;

static HowManyCheckNum: i32 = 50;
fn main() {
    let count_arc = Arc::new(Mutex::new(0));
    let flag_arc = Arc::new(Mutex::new(0));
    thread::spawn({
        let count_clone = Arc::clone(&count_arc);
        let flag_clone = Arc::clone(&flag_arc);
        move || {
            loop 
            {
                thread::sleep(Duration::from_millis(10));
                let mut num = count_clone.lock().unwrap();
                let mut flag = flag_clone.lock().unwrap();
                if *num % 15 == 0 && *flag == 1
                {
                    println!("FizzBuzz:{}", *num);
                    *flag = 0;
                }
                else if *num % 3 == 0 && *flag == 1 
                {
                    println!("Fizz:{}", *num);
                    *flag = 0;
                }
                else if *num % 5 == 0 && *flag == 1
                {
                    println!("Buzz:{}", *num);
                    *flag = 0;
                }
                else 
                {
                    continue;
                }
            }
        }
    });
    thread::spawn({
        let count_clone = Arc::clone(&count_arc);
        move || {
            loop 
            {
                thread::sleep(Duration::from_millis(50));
                let num = count_clone.lock().unwrap();
                if *num > HowManyCheckNum 
                {
                    println!("Check FizzBuzz TO {}", HowManyCheckNum);
                    exit(0);
                }
            }
        }
    });
    let count_clone = Arc::clone(&count_arc);
    let flag_clone = Arc::clone(&flag_arc);
    for _ in 1..99
    {
        thread::sleep(Duration::from_millis(10));
        let mut num = count_clone.lock().unwrap();
        let mut flag = flag_clone.lock().unwrap();
        if *flag == 1 
        {
            println!("{}", num);
        }
        *num = *num + 1;
        *flag = 1;
    }
}

実行結果

1
2
Fizz:3
4
Buzz:5
Fizz:6
7
8
Fizz:9
Buzz:10
11
Fizz:12
13
14
FizzBuzz:15
16
17
Fizz:18
19
Buzz:20
Fizz:21
22
23
Fizz:24
Buzz:25
26
Fizz:27
28
29
FizzBuzz:30
31
32
Fizz:33
34
Buzz:35
Fizz:36
37
38
Fizz:39
Buzz:40
41
Fizz:42
43
44
FizzBuzz:45
46
47
Fizz:48
49
Buzz:50
Fizz:51
52
53
Check FizzBuzz TO 50

成果物

以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?