ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.