more on reimplementing c++ timerqueue in rust

北慕城南 提交于 2020-08-10 19:18:13

问题


continuing this saga recoding a c++ task queue in rust. Is futures the right abstraction?

I have worked out how to store the function calls in a vector (I am ignoring all the set, sorting,... stuff for now). Lets just put some requests into a collection and get them run an a different thread.

so I have

pub struct TimerQueueItem {
    when: Instant,
    name: String,
    what: QIFunc,
}
type QIFunc = Box<dyn Fn() -> ()>;

struct TimerQueue {
    queue: Vec<TimerQueueItem>,
}

I can put these in a vector and then later loop over the vector and call them.

let x = || {
    println!("hello");
};
let y = || {
    println!("hello2");
};

let mut tq = TimerQueue::new();
tq.set(Box::new(x), String::from("yo"), Instant::now());
tq.set(Box::new(y), String::from("yo"), Instant::now());

tq.runq();

All works fine. But when I try to run the queue on a different thread I get told that I cannot move those QIFunc between threads.

fn thr(&mut self)->Sender<i32>{

    let (tx, rx) = channel::<i32>();
    thread::spawn(move ||{
            rx.recv();
            self.runq();
    });
    tx

}

gives

41  |         thread::spawn(move ||{
    |         ^^^^^^^^^^^^^ `(dyn std::ops::Fn() + 'static)` cannot be sent between threads safely

now I could randomly try all sorts of things but I am profoundly trying to get my brain around all this and mapping it to concepts I have from c++. I already feel like I am close to 'magic incantation' land where I cut and paste spells that I dont understand and they seem to work. So pointers to what I should read would be welcome. I have done a lot of reading tho. Just a steep learning curve I guess.

Feels like I am going to need a mutex on the TimerQueue object given thats its shared state between the clients and the worker thread. But that doesnt feel like what is being complained about here

来源:https://stackoverflow.com/questions/63094917/more-on-reimplementing-c-timerqueue-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!