0

In C++, we can write code like the following

void f1(int n)
{
    
}

std::thread t(f1, 1);

However, in Rust I can only do this through a closure, and it will involve capture.

fn foo(b: i32) {

}


let bb = 1;
let t1 = std::thread::spawn(move || foo(bb));

I wonder if there are some ways that I can directly create a thread that runs foo, and pass bb as its argument directly, like in C++.

If there are no way to do that, is this by design? Someone says closure it sugar, however, I found it is not replaceable here?

calvin
  • 2,125
  • 2
  • 21
  • 38
  • 2
    You *are* creating a thread that runs `foo(bb)`. Rust closures are zero-cost, the code in a closure is inlined whenever possible. Behind the scenes, both Rust and C++ are probably creating a shim that accepts a `void *x`. In C++ it's this shim that invokes `f1(1)`. In Rust, the shim gets the closure body pasted into it, which means that it too invokes `foo(1)`. It's the shim that gets passed to `pthread_create()` (or equivalent on non-Unix OS'es) and ultimately called by the operating system's threading machinery. – user4815162342 Nov 23 '21 at 16:44

1 Answers1

5

I wonder if there are some ways that I can directly create a thread that runs foo, and pass bb as its argument directly, like in C++.

No. std::thread::spawn can't accept arguments because Rust's type system does not support variadic functions. At best you could use a variadic macro to handle it for you but that seems... a lot of work for no gain at all.

If there are no way to do that, is this by design? Someone says closure it sugar, however, I found it is not replaceable here?

The article you're linking to says that closures are syntactic sugar for a function with an associated structure, not for whatever unspecified thing you think it is.

Masklinn
  • 34,759
  • 3
  • 38
  • 57