Error with threads in loop

I don't understand where this error comes from

    std::thread::spawn(move || {
        let mut data: bool = false;
        loop {
            if data {
                if !f() {
                    data = false;
            } else {
                if f() {
                    data = true;
                    std::thread::spawn(move || {

The console shows:


and if I try to remove the thread in the condition this works!
If you can help me.

std::thread::spawn starts a child thread and returns a JoinHandle. When JoinHandle is dropped (e.g. at the end of the function that started the thread), the child thread is detached. This means that the main thread of your program can finish before waiting for the child threads that it started. And when main thread finishes, the whole process will terminate (without waiting for child threads). If you want the program to wait for child threads, you'll need to call JoinHandle::join. An example from the docs:

use std::thread;

let handler = thread::spawn(|| {
    // thread code


See std::thread::spawn documentation.

It is not due to that. Indeed I have already joined the thread in the code.
the code is in a function that returns a join handle and join it.

Perhaps you could make a minimal example on and include a link to it here so we can try out the code ourselves? The code you have posted is clearly not complete, and we can't give any advice if the problem lies outside the code you posted.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.