Threads: How to extract strings from them

Hi,

I've been messing with it for a while but cannot find a solution. So I have an object that upon construction starts a thread, and within it receives a string. at the moment it is printing that string into file, which is then read by the master once all workers are joined. Is it possible to avoid this file writing and do something like :

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


#[derive(Clone)]
struct Obj {
    news: String,
}

#[derive(Clone)]
struct Foo(String);


impl Obj {

    fn new()->Self{

        let mut foo = Foo("".to_string());
	let card = Arc::new(Mutex::new(foo));
	let c_ard = card.clone();
        
       let handle =thread::spawn(move || {
            let mut guard = c_ard.lock().unwrap();
            guard.0 = "new string that is being recieved".to_string();
        });
        handle.join().unwrap();

        Obj{
            news: foo.0.clone(),

        }
    }
}


fn main (){
    let x = Obj::new();
    println!("::{}", x.news);
    
}

It does not need to be an object. I just need a shared String structure into which threads can write/append stuff (actually whatever you thing would be the best solution I'm all ears ).

Any help ?

The minimal change to get your example working;

let news = card.lock().unwrap().0.clone();
Obj{ news }

The documentation for spawn gives alternate ways (other than Mutex.) Using channels or the closures return value.

1 Like