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.
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)
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 off
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With