4

I'm working a lot with tokio and I've been using spawn_blocking for code that is going to block the thread. Then I saw the documentation for block_in_place and it seems like it's an unrestricted (Send, 'static) version of the former.

My question is, if I'm already on a threaded runtime, when is using block_in_place not advisable? What are the differences and advantages of each method of driving sync code? Can it be a problem if I block_in_place a lot, for example, in all my threads at the same time? How does it work?

I read all of the tokio documentation and didn't find the answer to these questions, so it felt right to ask here.

lsunsi
  • 41
  • 3
  • You should generally use spawn_blocking if you can. Use block_in_place if spawn_blocking can't work. – PitaJ Feb 04 '22 at 15:37

1 Answers1

2

If you can use spawn_blocking, use it.

block_in_place is less restrictive in that it does not require its argument to have 'static lifetime, but has two disadvantages. First, it makes executor perform additional work to move other tasks off the thread. Second, it prevents running other futures on the same task, which means it is pointless to join block_in_place future with other futures.

Can it be a problem if I block_in_place a lot, for example, in all my threads at the same time? How does it work?

You can read the implementation of block_in_place

It is not a problem to use block_in_place a lot except for additional overhead. It calls spawn_blocking internally prior to executing the function passed inside

cafce25
  • 15,907
  • 4
  • 25
  • 31
tla
  • 855
  • 1
  • 14