Q:

Rust program to access the main thread variable inside the worker thread

belongs to collection: Rust Threads Programs

0

In this program, we will create a variable inside the main thread and access created variable from the worker thread.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to access the main thread variable inside the worker thread is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to access the main thread 
// variable inside the worker thread

use std::thread;

fn main() 
{
    let num:i32=100;

    let handle = thread::spawn(move|| {
        println!("Num: {}", num);
    });		

    handle.join().unwrap();
    println!("Program finished");
}

Output:

$ rustc main.rs

$ ./main
Num: 100
Program finished

Explanation:

Here, we created a variable num inside the main() function. Then we created a thread using thread::spawn() function with the "move" keyword and printed the value of the num variable.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to send a message between threads... >>
<< Rust program to demonstrate the join() function in...