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

Rust | Thread Example: Write a program to access the main thread variable inside the worker thread.
Submitted by Nidhi, on November 02, 2021

Problem Solution:

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

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.

Rust Threads Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.