Thread lifetime

Hi guys,
I'm curious about thread lifetime.
We start thread with std:: thread ::spawn, so I understand this is the moment where the thread starts executing the function provided as an argument to the spawn method.
But when this thread ends its life?

The thread will shut down when the function you provide it returns.

Hi, thanks for the answer. Yes, I thought so, I just wasn't sure.
I'm asking this because I'm going through the tutorial from:

And there is a code like this:

std:: thread ::spawn(||{});

What's the point of doing it if the thread will finish its life immediately?

It is a place-holder. More will be added to the thread later.

So how shall I understand this code?
Because according to what you've said and to what I understand, the thread will execute the closure and finish its life.
But now you're saying that it is a placeholder, meaning that the thread will not end its lifetime after executing that provided closure.
How to understand that?

No, it will end its life immediately. What I mean with placeholder is that the code example will later be modified such that the thread actually does something.


Ah, OK, thanks

The docs for std::thread::spawn() talks about the guarantees and behaviour of a spawned thread in more detail:

Spawns a new thread, returning a JoinHandle for it.

The join handle will implicitly detach the child thread upon being dropped. In this case, the child thread may outlive the parent (unless the parent thread is the main thread; the whole process is terminated when the main thread finishes). Additionally, the join handle provides a join method that can be used to join the child thread. If the child thread panics, join will return an Err containing the argument given to panic .

Hi, tbh I fail to see relevance of your comment to what I was asking for. Sorry.

Doesn't the thread also shut down when the main routine ends?

Yes, that's true. If main exits, all other threads are killed.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.