Scoped Threads and question about lifetime

std::thread::scope(|s| {
std::thread::spawn(|s|{do_something_else()});//This thread

Is the thread spawn by invoking std::thread::spawn also guaranteed to last only as long as the scope lasts?

No, that's only the case for threads spawned by the scope. After all, how would arbitrary threads know about arbitrary, unrelated scopes?


Don't wan't to go into academic discussion here, but those are not arbitrary threads in unrelated scopes.Clearly the scope is well defined and every thread in that scope could be detected "somehow" - ideally by magic.

But thank you for your answer. I thought so, I just wanted to make sure I got that right.

They are in unrelated scopes, because that's what std::thread::spawn does -- hence the 'static bounds and detaching nature of its JoinHandle, in contrast with Scope::spawn and its ScopedJoinHandle.

They serve different needs; use which is needed.

1 Like

That's something that doesn't work in programming. You may create a bunch of rules which would impress newbies which would see how everything “magically” works.

But when you start doing bigger programs you find crazy warts (like that infamous fact that PHP thinks strings "1e3" and "1000" are equal).

Then you spend the rest of your career trying to get rid of that “magic” (which doesn't always work: PHP doesn't have < alternative which can be used to reliably sort objects, e.g.).

Rust is not designed to impress newcomers, it tries to ensure that if it ever does something magical (like calling drop for example) then this magic works not just for newbies but for everyone.

That rarely happens thus Rust doesn't have a lot of magic.

Clearly you didn't realize that it is a sarcasm...

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.