Q:

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

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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now