0
votes

I am rewriting a c++ project in rust as my first non-tiny rust program. I thought I would start with a simple but key gnarly piece of code.

Its a queue of std::packaged_tasks that run at specific times. A client says

running_func_fut_ = bus_->TimerQueue().QueueTask(std::chrono::milliseconds(func_def.delay),
    [this, func, &unit]()
    {
        func(this, &unit);
        Done();
    }, trace);

func is a std::function, but they key point is that as far as the queue is concerned is queuing up a lambda (closure in rust speak )

It returns a std::future which the client can ignore or can hang onto. If they hang onto it they can see if the task completed yet. (It could return a result but in my current use case the functions are all void, the client just needs to know if the task completed). All the tasks run on a single dedicated thread. The QueueTask method wraps the passed lambda up in a packaged_task and then places it in a multiset of objects that say when and what to run.

I am reading the rust docs and it seems that futures encapsulate both the callable object and the 'get me the result' mechanism.

So I think I need a BTreeSet (I need the queue sorted by launch time so I can pick the next one to run) of futures, but I am not even sure how to declare one of those. SO before I dive into the deep end of futures, is this the right approach? Is there a better , more natural, abstraction for rust?

1
A queue sorted by launch time so you can pick the next one to run sounds like a job for a priority queue, not a hash set. The Rust standard library has a binary heap with examples. (There’s also a B-tree set if you need more operations.)Ry-
they are sorted by execution time, I go to sleep on a condition variable with a timeout set to the time of the first item (and wake up and recheck the sleep time when a new item is posted) Its not based on fifo or prioritypm100
A hash set isn’t ordered.Ry-
sry your are right, a btreeset is what I meantpm100

1 Answers

0
votes

For the output, you probably do want a Future. However, for the input, you probably want a function object (Box<dyn FnOnce(...)>); see https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html.