Create control object at start of application

I have Webserver that has to do some computation on every request. The computation is done by a Control object that is !Send and !Sync. The setup of the controller requires 4s, each request is currently 100ms.

I would like to create the control at the start of the application. I think that it would be necessary that a separate thread creates and owns the control and other threads can communicate with that thread using channels. Is that correct?

What libs and technology should I use?

I don't think you can share anything between threads if it's !Send. If it is Send but !Sync, you can wrap it in an Arc<Mutex<T>> and initialize it using lazy_static! or once_cell.

It is neither Send nor Sync. The idea is that one thread ownes the control and other threads send requests and read responses

Not sure what it means that the computation is "done using" this control object, but if it's !Sync, then there's really no way to share it between threads in any sound manner. Can you set up the computation such that e.g. an mpsc::channel() sender-receiver pair can push/pull the necessary data from and to it?

1 Like

Example

let mut control = Control::setup(); // expensive setup, independent from input
let output1 = control.compute(input1); // inexpensive computation
let output2 = control.compute(input2); // inexpensive computation, control can be reused

The input / output can be sent through channels. The control struct will be owned by a single thread and the communication will be via some channels.

My question is what tools should I use to setup such a system.

You could use the channels from std::sync::mpsc.

Another option that may be viable is to use thread local variables so each thread gets its own control object.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.