Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Rust optimize away unused function arguments?

I have a function of type

f: fn(x: SomeType, y: Arc<()>) -> ISupposeTheReturnTypeDoesNotMatter

when compiled (with or without optimization), will the y be optimized away?

The intention of the y is to limit the number of the running instances of f, if y is referenced too many times, the caller of f will not call f until the reference count of y becomes lower.

Edit: clarification on my intention

The intention is to keep the number of running http requests (represented by the above f) in control, the pseudo code looks like this:

let y = Arc::new(());
let all_jobs_to_be_done = vector_of_many_jobs;
loop {
    while y.strong_count() < some_predefined_limit {
        // we have some free slots, fill them up with instances of f,
        // f is passed with a clone of y,
        // so that the running of f would increase the ref count,
        // and the death of the worker thread would decrease the ref count
        let work = all_jobs_to_be_done.pop();
        let ticket = y.clone();
        spawn_work(move || {f(work, ticket)});
    }

    sleep_for_a_few_seconds();
}

The reason for this seemingly hacky work around is that I cannot find a library that meets my needs (consume a changing work queue with bounded amount of async (tokio) workers, and requeue the work if the job fails)

like image 919
Incömplete Avatar asked Sep 02 '20 01:09

Incömplete


1 Answers

Will Rust optimize away unused function arguments?

Yes, LLVM (the backend for rustc) is able to optimize away unused variables when removing them does not change program behavior, although nothing guarantees it will do it. rustc has some passes before LLVM too, but the same applies.

Knowing what exactly counts as program behavior is tricky business. However, multi-threaded primitives used in refcounting mechanics are usually the sort of thing that cannot be optimized away for good reason. Refer to the Rust reference for more information (other resources that might help are the nomicon, the different GitHub repos, the Rust fora, the C++11 memory model which Rust uses, etc.).

On the other hand, if you are asking about what are the semantics of the language when it encounters unused parameters, then no, Rust does not ignore them (and hopefully never will!).

will the y be optimized away?

No, it is a type with side effects. For instance, dropping it requires running non-trivial code.

The intention of the y is to limit the number of the running instances of f

Such an arrangement does not limit how many threads are running f since Arc is not a mutex and, even if it were some kind of mutex, you could construct as many independent ones as you wanted.

like image 103
Acorn Avatar answered Oct 20 '22 16:10

Acorn