Home > database >  How can I make two functions in Rust run upon spawning a thread?
How can I make two functions in Rust run upon spawning a thread?

Time:09-08

I have the following two functions that I want to call upon spawning the Librarian thread, but only the first function is called. Is there a way I can make both functions call?

let Librarian = thread::spawn(move || {
    libReceiveOrder();
    libReceiveBooks();
});

CodePudding user response:

As I understand, you want to run two functions libReceiveOrders and libReceiveBooks at once. There are two ways I can recommend you to make that work.

A - use separate thread per function

This is simple. Just create two more threads, one - for libReceiveOrders and another one for libReceiveBooks. This will make them run and work with queues.

Here is full working example

B - use tokio's async methods and especially, tokio::select!

This uses one thread for both functions with tokio::select! macro. This simplifies synchronization between them, as they can easily share some state without Mutex. But this also makes your code harder to scale as it utilizes only a single thread for both works. Depend's on your goals what is better here.

Here is full working example

  • Related